T-SQL将2行合并为1

时间:2016-08-31 11:52:13

标签: tsql sql-server-2012

我有一张桌子,最后我有两行,但我需要一行中两行的总数据,我不能使用分组,因为我得到通常必须在选择列表或包含在group by子句中。

DECLARE @Test TABLE 

(
FirstName NVARCHAR(10)
,Ref NVARCHAR (4)
,UserName NVARCHAR(30)
,File1 INT
,File2 INT
,ID INT
,Active Bit DEFAULT 0


)
INSERT INTO @Test VALUES ('John','AAAB','AAA Admin',5,10,677,1)
INSERT INTO @Test VALUES ('John (P)','AAAC','AAAC Admin',6,15,765,1)
INSERT INTO @Test VALUES ('John Admin','AAAG','AAA Admin',6,15,765,0)
INSERT INTO @Test VALUES ('Jane','AAUD','AAA Admin',6,15,765,0)
INSERT INTO @Test VALUES ('Jenny','AAOZ','AAA Admin',6,15,765,0)

;WITH CTE
 AS
 (
    SELECT *,ROW_NUMBER() OVER(Partition by FirstName Order by ID) RN
    from @Test
 )
 SELECT * FROM CTE
 WHERE RN=1 AND Active = 1
 ORDER BY ID DESC

[![Results][1]][1]

enter image description here

INSERTS 3,4,5中的File1和File2值是重复数据,结果中不需要。

文字:

FirstName   Ref UserName    File1   File2   ID  Active  RN
John (P)    AAAC    AAAC Admin  6   15  765 1   1
John    AAAB    AAA Admin   5   10  677 1   1

预期产出:

enter image description here

1 个答案:

答案 0 :(得分:1)

I'm not sure what you want.

DECLARE @Test TABLE 
(
FirstName NVARCHAR(10)
,Ref NVARCHAR (4)
,UserName NVARCHAR(30)
,File1 INT
,File2 INT
,ID INT
,Active Bit DEFAULT 0
)
INSERT INTO @Test VALUES ('John','AAAB','AAA Admin',5,10,677,1)
INSERT INTO @Test VALUES ('John (P)','AAAC','AAAC Admin',6,15,765,1)
INSERT INTO @Test VALUES ('John Admin','AAAG','AAA Admin',6,15,765,0)
INSERT INTO @Test VALUES ('Jane','AAUD','AAA Admin',6,15,765,0)
INSERT INTO @Test VALUES ('Jenny','AAOZ','AAA Admin',6,15,765,0)

;WITH CTE
AS
(
    SELECT
        IIF(Tmp = 0, A.FirstName, SUBSTRING(A.FirstName, 0, A.Tmp)) FirstName,
        A.File1,
        A.File2
    FROM
    (
        SELECT 
            *,
            CHARINDEX(' ', FirstName, 0) Tmp
        FROM 
            @Test
        WHERE
            Active = 1
    ) A
)   

SELECT
    A.FirstName,
    SUM(A.File1) File1,
    SUM(A.File2) File2
FROM
    CTE A
GROUP BY    
    A.FirstName

Result:

FirstName   File1   File2
John        11      25