单行上SQL表的结果(SQLServer)

时间:2013-11-08 11:31:34

标签: sql

我的SQL表(TOTAL_PAR_STATUT)包含以下字段:

DISTRIBUTEUR_ID - receptionDate - STATUS_CHAMP_ID - TOTAL_BY_STATUS

执行查询时:

SELECT tps.DISTRIBUTEUR_ID,
   tps.receptionDate,
   tps.STATUS_CHAMP_ID,
   tps.TOTAL_BY_STATUS
FROM TOTAL_PAR_STATUT tps
WHERE tps.receptionDate between '06-10-2013 00:00:00' AND '06-10-2013 23:59:59'
       AND tps.DISTRIBUTEUR_ID = 1 
       AND STATUS_CHAMP_ID IN (1,2,3,9,10,11,7)
GROUP BY tps.DISTRIBUTEUR_ID, tps.receptionDate, tps.TOTAL_BY_STATUS, tps.STATUS_CHAMP_ID;

它给了我以下结果:

 DISTRIBUTEUR_ID --- receptionDate --- STATUS_CHAMP_ID --- TOTAL_BY_STATUS

     1   ---    '2013-10-06 00:00:00' --- 3  ---            1

     1   ---    '2013-10-06 00:00:00' --- 1  ---            13

我想将结果分组到一行中,以便为我提供以下内容:

     DISTRIBUTEUR_ID --- receptionDate --- TOTAL_WHERE_STATUS_3 --- TOTAL_WHERE_STATUS_1

         1  --- '2013-10-06 00:00:00'   ---  1 ---                  13

谢谢。

1 个答案:

答案 0 :(得分:1)

使用SUM(CASE WHEN ...)

这未经过测试,但应该让您了解如何获得您想要的东西:

SELECT tps.DISTRIBUTEUR_ID,
   tps.receptionDate,
   SUM(CASE WHEN tps.STATUS_CHAMP_ID = 3 THEN 1 ELSE 0 END)[TOTAL_WHERE_STATUS_3],
   SUM(CASE WHEN tps.STATUS_CHAMP_ID = 1 THEN 1 ELSE 0 END)[TOTAL_WHERE_STATUS_1],
FROM TOTAL_PAR_STATUT tps
WHERE tps.receptionDate between '06-10-2013 00:00:00' AND '06-10-2013 23:59:59'
       AND tps.DISTRIBUTEUR_ID = 1 
       AND STATUS_CHAMP_ID IN (1,2,3,9,10,11,7)
GROUP BY tps.DISTRIBUTEUR_ID, tps.receptionDate