2012-02-10 161 views
1

讓我們有一個查詢SQL查詢值重複

SELECT `name`, `companyid` 
    FROM `users` 

它的結果可能是

Peter | 1 
Michael | 1 
Tom  | 2 
John | 2 
Ian  | 4 

是否有可能創造一個爲每個唯一companyid值將增加一排

查詢結果
System | <current companyId> 

所以結果會是

Peter | 1 
Michael | 1 
System | 1 
Tom  | 2 
John | 2 
System | 2 
Ian  | 4 
System | 4 
+3

什麼RDBMS這是什麼? – 2012-02-10 14:42:26

回答

3
SELECT * FROM 
( 
    SELECT name,companyid FROM users 
    UNION ALL 
    SELECT DISTINCT 'System', companyid FROM users 
) 
ORDER BY companyid 
+0

你不需要使用「groupid by groupid」子句嗎? – Bogdan 2012-02-10 14:43:15

+0

沒有第二個選擇被標記爲DISTINCT – Matten 2012-02-10 14:45:59

+0

@Bogdan:'DISTINCT' – 2012-02-10 14:47:22

1

如果我理解正確你,這會工作:

select * 
from 
(
    select name, companyid 
    from users 

    union all 

    select distinct 'System', companyid 
    from users 
)a 
order by companyid 
1
SELECT name,companyid FROM users 
UNION ALL 
(
    SELECT 'System' as name, companyid 
    FROM users 
    GROUP BY companyid 
) 

應該這樣做

1

也許是這樣的:

一是一些測試數據:

DECLARE @tbl TABLE(name VARCHAR(100),companyId INT) 
INSERT INTO @tbl (name,companyId) 
VALUES 
    ('Peter',1), 
    ('Michael',1), 
    ('Tom',2), 
    ('Ian',4) 

然後像這樣的查詢:

;WITH CTE AS 
(
    SELECT 
     RANK() OVER(PARTITION BY companyId ORDER BY name) RowNbr, 
     tbl.companyId, 
     'System' AS name 
    FROM 
     @tbl AS tbl 
) 
SELECT 
    tbl.name, 
    tbl.companyId 
FROM 
    @tbl AS tbl 
UNION ALL 
SELECT 
    CTE.name, 
    CTE.companyId 
FROM 
    CTE 
WHERE 
    CTE.RowNbr=1 
1
SELECT name, companyid 
    FROM users 
UNION 
SELECT 'System' AS name, companyid 
    FROM users;