在GROUP BY期间过去的MSSQL计数日期

时间:2012-02-14 13:42:31

标签: sql sql-server database

我在MSSQL-Server上有一个包含几个字段的表:

fieldA,fieldB,fieldC,DateTimeField

现在我正在做这样的选择:

SELECT fieldA,fieldB,fieldC, max(DateTimeField),min(DateTimeField),
(count(*) - count(DateTimeField)) as DateTimeFieldIsNull
FROM table 
GROUP BY fieldA, fieldB, fieldC

效果很好。

现在我想要计算过去或其他列中未来的所有DateTimeField

是否有表演方式? (甚至可能没有加入)?

Thnx,Harry

4 个答案:

答案 0 :(得分:5)

只需添加COUNT / CASE构造即可。
从COUNT忽略的隐含ELSE中获取NULL

COUNT(CASE WHEN DateTimeField > GETDATE() THEN 1 END) AS FutureDates,
COUNT(CASE WHEN DateTimeField < GETDATE() THEN 1 END) AS PastDates,

答案 1 :(得分:2)

SELECT fieldA,fieldB,fieldC, max(DateTimeField),min(DateTimeField),
(count(*) - count(DateTimeField)) as DateTimeFieldIsNull
, COUNT(CASE WHEN DateTimeField > GETDATE()  THEN 1 END) AS 'ABC'
, COUNT(CASE WHEN DateTimeField < GETDATE()  THEN 1 END) AS 'XYZ'
FROM table 
GROUP BY fieldA, fieldB, fieldC;

答案 2 :(得分:1)

您可以使用2个子查询来获取此结果集:

SELECT fieldA,fieldB,fieldC, max(DateTimeField),min(DateTimeField),
(count(*) - count(DateTimeField)) as DateTimeFieldIsNull
,(SELECT COUNT(DateTimeField)
  FROM table
  WHERE DateTimeField<GETDATE()
  AND t.fieldA=fieldA
  AND t.fieldB=fieldB
  AND t.fieldC=fieldC) as PastDates
,(SELECT COUNT(DateTimeField)
  FROM table
  WHERE DateTimeField>=GETDATE()
  AND t.fieldA=fieldA
  AND t.fieldB=fieldB
  AND t.fieldC=fieldC) as FutureDates
FROM table t
GROUP BY fieldA, fieldB, fieldC

答案 3 :(得分:1)

这样的东西?:

SELECT  fieldA, fieldB, fieldC, 
        MAX(DateTimeField), MIN(DateTimeField),
        (COUNT(*) - COUNT(DateTimeField)) as DateTimeFieldIsNull,
        SUM(CASE WHEN DateTimeField < GETDATE() THEN 1 END) DateTimeFieldInThePast,
        SUM(CASE WHEN DateTimeField > GETDATE() THEN 1 END) DateTimeFieldInTheFuture
FROM table 
GROUP BY fieldA, fieldB, fieldC