选择具有group by子句的新列

时间:2016-04-01 05:51:58

标签: sql sql-server group-by

我想用group by子句选择另一个带有sum或count函数的列。

SELECT t1.[09to12PM], t2.[12to15PM], t3.[15to17PM], t4.[17to23PM]
FROM
  (SELECT COUNT (Premark) AS [09to12PM]
   FROM saree_order_stages
   WHERE Premark LIKE '%ready to go%' AND Premark != 'not ready to go'
     AND pdate>='2016-03-29 09:00:00' AND Pdate <='2016-03-29 12:00:00') t1,

  (SELECT COUNT (Premark) AS [12to15PM]
   FROM saree_order_stages
   WHERE Premark LIKE '%ready to go%' AND Premark != 'not ready to go'
     AND pdate>='2016-03-29 12:00:00' AND Pdate <='2016-03-29 15:00:00') t2,

  (SELECT COUNT (Premark) AS [15to17PM]
   FROM saree_order_stages
   WHERE Premark LIKE '%ready to go%' AND Premark != 'not ready to go'
     AND pdate>='2016-03-29 15:00:00' AND Pdate <='2016-03-29 17:00:00') t3,

  (SELECT COUNT (Premark) AS [17to23PM]
   FROM saree_order_stages
   WHERE Premark LIKE '%ready to go%' AND Premark != 'not ready to go'
     AND pdate>='2016-03-29 17:00:00' AND Pdate <='2016-03-29 23:00:00') t4
GROUP BY t1.[09to12PM], t2.[12to15PM], t3.[15to17PM], t4.[17to23PM]

这里结果显示了这个

09to12PM  12to15PM 15to17PM 17to23PM
23         21        15        19

我们希望添加一个列名,就像这样。 并显示如下数据。

name 09to12PM  12to15PM 15to17PM 17to23PM
amit   23         21        15        19 
sumit  11         22        11        45
raj    14         4         5         67

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合简化查询:

SELECT
    name,
    [09to12PM] = SUM(CASE WHEN pdate>='2016-03-29 09:00:00' AND Pdate <='2016-03-29 12:00:00' THEN 1 ELSE 0 END),
    [12to15PM] = SUM(CASE WHEN pdate>='2016-03-29 12:00:00' AND Pdate <='2016-03-29 15:00:00' THEN 1 ELSE 0 END),
    [15to17PM] = SUM(CASE WHEN pdate>='2016-03-29 15:00:00' AND Pdate <='2016-03-29 17:00:00' THEN 1 ELSE 0 END),
    [17to23PM] = SUM(CASE WHEN pdate>='2016-03-29 17:00:00' AND Pdate <='2016-03-29 23:00:00' THEN 1 ELSE 0 END)
FROM saree_order_stages
WHERE
    Premark LIKE '%ready to go%'
    AND Premark != 'not ready to go'
    AND CAST(pdate AS DATE) = '2016-03-29'
GROUP BY name