group by在我的查询中不起作用

时间:2017-05-02 09:57:33

标签: sql-server-2008 tsql group-by

以下是我想在ReadyDate上总计的查询,invDate表示所有数据都具有相同的readydate和invdate,则total将是这两天之间所有总数的总和

READYDATE   Total     INVDATE     FIXED  TWO_MAN    THREE_MAN
2017-01-30  0.00      2017-02-12    NULL    1       0
2017-01-30  12102.20  2017-02-12    NULL    1       0
2017-01-30  1950.30   2017-02-12    NULL    0       1
2017-01-30  0.00      2017-03-26    NULL    1       0
2017-01-31  0.00      2017-02-12    NULL    1       0
2017-01-31  10451.90  2017-02-12    NULL    1       0
2017-01-31  1300.20   2017-02-12    NULL    0       1
2017-02-01  10451.90  2017-02-12    NULL    1       0
2017-02-01  1950.30   2017-02-12    NULL    0       1
2017-02-02  12652.30  2017-02-12    NULL    1       0

正确的意志

 READYDATE  Total        INVDATE       FIXED    TWO_MAN THREE_MAN
 2017-01-30 14052.00    2017-02-12     NULL      1        0

因为总数将是readydate和invdate 14052.50

我的查询在

之下
 SELECT    READYDATE, SUM(TOTAL) AS Total, INVDATE, 
 case when TOTAL='1495.38' then TOTAL else NULL END AS FIXED, 
 case when TOTAL<600 then '1' else '0' END AS TWO_MAN, 
 case when TOTAL>=600 then '1' else '0' END AS THREE_MAN 
 FROM orde_ WHERE CLIENTNUM='WAY' AND INVDATE>='20170101'
 GROUP BY READYDATE,INVDATE,TOTAL
ORDER BY READYDATE
你能告诉我我做错了吗

1 个答案:

答案 0 :(得分:0)

试试这个

DECLARE @tbl TABLE(
READYDATE   DATE
,Total      MONEY
,INVDATE    DATE
)

INSERT INTO @tbl
        ( READYDATE
        ,Total
        ,INVDATE
        )
VALUES
('2017-01-30',0.00, '2017-02-12')
,('2017-01-30',12102.20, '2017-02-12')
,('2017-01-30',1950.30, '2017-02-12')
,('2017-01-30',0.00, '2017-03-26')
,('2017-01-31',0.00, '2017-02-12')
,('2017-01-31',10451.90, '2017-02-12')
,('2017-01-31',1300.20, '2017-02-12')
,('2017-02-01',10451.90, '2017-02-12')
,('2017-02-01',1950.30, '2017-02-12')
,('2017-02-02',12652.30, '2017-02-12')

;WITH cteX
AS
(
SELECT
    T.READYDATE
   ,T.INVDATE
   ,SUM(T.Total) 'Total'
FROM @tbl T
GROUP BY
    T.READYDATE
   ,T.INVDATE
)
SELECT
     X.READYDATE
    ,X.Total
    ,X.INVDATE
    ,case when TOTAL='1495.38' then TOTAL else NULL END AS FIXED
    ,case when TOTAL<600 then '1' else '0' END AS TWO_MAN
    ,case when TOTAL>=600 then '1' else '0' END AS THREE_MAN 
FROM cteX X
ORDER BY
    X.READYDATE