0

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

DISTRIBUTEUR_ID -- 接收日期 -- 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

谢谢你。

4

1 回答 1

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
于 2013-11-08T11:49:10.007 回答