多个日期与计数

时间:2015-01-15 17:35:19

标签: sql

我有3列

  • Order_ID上

  • Activation_Date

  • Order_Received_Date

因此,如果我明确计算Order_Received_Date上的所有order_ID,我将获得“订单数量”同样,如果我明确计算Activation_Date上的所有order_ID,我将获得“激活次数”

我想要的是两列名为“#Orders”和“#Activations”

感谢任何输入,谢谢

2 个答案:

答案 0 :(得分:1)

我使用union all进行此类计算。以下是标准SQL,因此它应该适用于任何数据库:

select thedate, sum(r) as numorders, sum(a) as numactivations
from (select activation_date as thedate, 1 as a, 0 as r from table t
      union all
      select order_received_date, 0, 1 from table t
     ) t
group by thedate
order by thedate;

答案 1 :(得分:0)

如果我理解正确,我猜以下查询可能会帮助您解决此问题:

SELECT 
    OrderID,
    ActivationDate,
    OrderReceivedDate,
    COUNT(OrderID) OVER (),
    COUNT(ActivationDate) OVER ()
FROM
(
    SELECT 1 AS OrderID, '2014-01-01' AS ActivationDate, '2013-12-15' AS OrderReceivedDate UNION
    SELECT 2 AS OrderID, NULL AS ActivationDate, '2013-12-19' AS OrderReceivedDate UNION
    SELECT 3 AS OrderID, '2014-03-01' AS ActivationDate, '2013-12-17' AS OrderReceivedDate UNION
    SELECT 4 AS OrderID, '2014-04-01' AS ActivationDate, '2013-12-03' AS OrderReceivedDate
) t

我希望这可以帮助你...