Sql查询值重复

时间:2012-02-10 14:38:45

标签: 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

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

如果我理解正确,这将有效:

select *
from
(
    select name, companyid
    from users

    union all

    select distinct 'System', companyid
    from users
)a
order by companyid

答案 2 :(得分:1)

SELECT name,companyid FROM users
UNION ALL
(
  SELECT 'System' as name, companyid 
  FROM users
  GROUP BY companyid
)

应该这样做

答案 3 :(得分: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

答案 4 :(得分:1)

SELECT name, companyid
  FROM users
UNION
SELECT 'System' AS name, companyid
  FROM users;