SQL Server案例语句和聚合函数

时间:2014-08-04 05:23:22

标签: sql sql-server sum case-statement

我有以下表格数据:

SELECT [Quote ID], [Deductible Plan], [Age ID], [Number of Members] 
FROM finalResult_001

1381    $750 Deductible Plan    Age 65      10
1381    $750 Deductible Plan    Age 85+     10
1371    $150 Deductible Plan    Age 65      10
1371    $150 Deductible Plan    Age 85+     10

我正在寻找以下结果:

Quote ID Deductible Plan       Age 65      Age 85+
1381    $750 Deductible Plan    10          10
1371    $150 Deductible Plan    10          10

我希望按引用ID和免赔额计划分组,并且应该按年龄ID列加总,但是我不知道该怎么做,这是我的尝试:

SELECT [Quote ID], [Deductible Plan],

case when [Age ID] = 'Age 65' THEN SUM([Number of Members]) else 0 END AS [Age 65],   
case when [Age ID] = 'Age 85+' THEN SUM([Number of Members]) else 0 END AS [Age 85+]

FROM finalResult_001
GROUP BY [Quote ID], [Age ID], [Deductible Plan]

结果:

Quote ID Deductible Plan        Age 65      Age 85+
1381    $750 Deductible Plan    0           10
1381    $750 Deductible Plan    10          0
1371    $150 Deductible Plan    0           10
1371    $150 Deductible Plan    10          0

我如何将年龄ID加起来给我一个resule:

Quote ID Deductible Plan        Age 65      Age 85+
1381    $750 Deductible Plan    10          10
1371    $150 Deductible Plan    10          10

2 个答案:

答案 0 :(得分:4)

将CASE应用于[Number of Members]而不是SUM([Number of Members]),不要按[Age ID]分组:

SELECT
  [Quote ID],
  [Deductible Plan],
  SUM(case when [Age ID] = 'Age 65'  THEN [Number of Members] else 0 END) AS [Age 65],   
  SUM(case when [Age ID] = 'Age 85+' THEN [Number of Members] else 0 END) AS [Age 85+]
FROM dbo.finalResult_001
GROUP BY [Quote ID], [Deductible Plan]
;

答案 1 :(得分:1)

DECLARE @t Table (QuoteID INT,Deductible VARCHAR(100),Age INT,AgeID INT)

INSERT INTO @t(QuoteID,Deductible,Age,AgeID)values (1381,'$750 Deductible Plan',0,10)
INSERT INTO @t(QuoteID,Deductible,Age,AgeID)values (1381,'$150 Deductible Plan',10,0)
INSERT INTO @t(QuoteID,Deductible,Age,AgeID)values (1371,'$750 Deductible Plan',0,10)
INSERT INTO @t(QuoteID,Deductible,Age,AgeID)values (1371,'$150 Deductible Plan',10,0)

;WITH CTE
AS (
    SELECT DISTINCT t.QuoteID
        ,MAX(tt.Age) AA
        ,MAX(ttt.Ageid) AAA
        ,ROW_NUMBER() OVER (
            PARTITION BY t.Deductible ORDER BY t.Deductible
            ) RN
        ,t.Deductible
    FROM @t t
    INNER JOIN (
        SELECT Age
            ,QuoteID
        FROM @t
        GROUP BY QuoteID
            ,Deductible
            ,Age
            ,AgeID
        ) tt ON tt.QuoteID = t.QuoteID
    INNER JOIN (
        SELECT AgeID
            ,QuoteID
            ,Deductible
        FROM @t
        GROUP BY QuoteID
            ,Deductible
            ,Age
            ,AgeID
        ) ttt ON ttt.QuoteID = t.QuoteID
    GROUP BY t.QuoteID
        ,t.Deductible
    )
SELECT C.QuoteID
    ,C.Deductible
    ,C.AA AGE
    ,C.AAA Age1
FROM Cte C
WHERE RN = 1