t-sql分组查询

时间:2010-04-16 18:07:21

标签: sql-server sql-server-2005 tsql

基于下表

Name
---------
A
A
A
B
B
C
C
C

我想在此表中添加另一个名为“OnGoing”的列,并且值应该替换为每组名称。 只有两个值'X'和'Y'。所以表格看起来像

Name     OnGoing
----------------
A        X
A        X
A        X 
B        Y
B        Y
C        X
C        X 
C        X

如何编写可以替换每组名称的值的查询。

3 个答案:

答案 0 :(得分:5)

这样的东西
DECLARE @Table TABLE(
        Name VARCHAR(10)
)

INSERT INTO @Table SELECT 'A'
INSERT INTO @Table SELECT 'A' 
INSERT INTO @Table SELECT 'A' 
INSERT INTO @Table SELECT 'B' 
INSERT INTO @Table SELECT 'B' 
INSERT INTO @Table SELECT 'C' 
INSERT INTO @Table SELECT 'C' 
INSERT INTO @Table SELECT 'C' 

SELECT  *,
        CASE 
            WHEN RowNum % 2 = 0 
                THEN 'Y'
            ELSE 'X'
        END
FROM    @Table t INNER JOIN
        (
            SELECT  Name,
                    ROW_NUMBER() OVER (ORDER BY Name) RowNum
            FROM    @Table
            GROUP BY Name
        ) sub ON t.Name = sub.Name

答案 1 :(得分:2)

更改您的表格以包含新列:

ALTER TABLE YourTable ADD
    OnGoing char(1) NULL
GO

然后试试这个:

DECLARE @YourTable table (Name char(1), OnGoing char(1))
INSERT @YourTable Values ('A',NULL)
INSERT @YourTable Values ('A',NULL)
INSERT @YourTable Values ('A',NULL)
INSERT @YourTable Values ('B',NULL)
INSERT @YourTable Values ('B',NULL)
INSERT @YourTable Values ('C',NULL)
INSERT @YourTable Values ('C',NULL)
INSERT @YourTable Values ('C',NULL)


;WITH TableRows AS
(
 SELECT
     *, ROW_NUMBER() OVER(ORDER BY Name) AS RowID
     FROM (SELECT DISTINCT
               *
               FROM @YourTable
          ) dt
)
UPDATE y
    SET OnGoing=CASE
                   WHEN r.RowID % 2 = 1 THEN 'X'
                   ELSE 'Y'
                END
    FROM @YourTable           y
        INNER JOIN TableRows  r ON y.Name=r.Name

SELECT * FROM @YourTable

输出:

Name OnGoing
---- -------
A    X
A    X
A    X
B    Y
B    Y
C    X
C    X
C    X

(8 row(s) affected)

答案 2 :(得分:0)

这样可以解决问题:

select
    t1.Name,
    sub1.OnGoing 
from
    TableOne t1
    INNER JOIN 
(select
    Name,
    CASE RANK() over (order by Name) % 2
    WHEN 0 THEN 'Y'
    WHEN 1 THEN 'X'
    END as OnGoing
from 
    TableOne 
group by Name) sub1 ON sub1.Name = t1.Name

这是我测试的实际输出:

Name OnGoing
---- -------
A    X
A    X
A    X
B    Y
B    Y
C    X
C    X
C    X