选择日期和计数,按日期分组-如何显示带有NULL计数的日期?

时间:2019-03-29 23:45:20

标签: tsql subquery distinct aggregate-functions

SELECT
    CAST(c.DT AS DATE) AS 'Date'
    , COUNT(p.PatternID) AS 'Count'
FROM CalendarMain c
LEFT OUTER JOIN Pattern p
    ON c.DT = p.PatternDate
INNER JOIN Result r
    ON p.PatternID = r.PatternID
INNER JOIN Detail d
    ON p.PatternID = d.PatternID
WHERE r.Type = 7
AND d.Panel = 501
AND CAST(c.DT AS DATE) 
    BETWEEN '20190101' AND '20190201'
GROUP BY CAST(c.DT AS DATE)
ORDER BY CAST(c.DT AS DATE)

上面的查询不适用于我。它仍然会跳过c.DT的COUNT为NULL的日子。

c.DT和p.PatternDate都是时间DateTime,尽管c.DT不能为NULL。它实际上是表的PK。从2015年到2049年的每一天,它都被填充为DateTimes,因此存在这些天的记录。

我注意到的另一个奇怪的事情是,当我加入C.DT = p.PatternDate而没有CAST或CONVERT转换为Date样式时,什么也没有返回。不确定为什么它们都是DateTimes。

1 个答案:

答案 0 :(得分:0)

这里有几件事要谈。目前尚不清楚您实际要计算的内容。如果它是2019年1月的每日“模式”数,则:

  • 您的BETWEEN也将计算2月1日发生的任何活动,
  • 一个模式可能有多个结果,可能导致错误计数
  • 一个模式可能包含多个细节,可能会导致计数错误
  • 如果一个模式显示3个合格结果以及4个详细信息,则将得到它们的叉积。您的数量将为12。

我要假设:

  • 无论细节和结果的数量如何,您只需要不同数量的模式。
  • 您只想要一月的活动

data = [['Thursday 4 January', 11.58, 0.38], ['Thursday 4 January', 16.95, 0.73], ['Thursday 4 January', 23.68, 0.02], ['Friday 5 January', 6.48, 0.83], ['Friday 5 January', 12.42, 0.33]] dic={'day':[],'min':[],'max':[]} for i in data : dic['day']+=[i[0]] dic['min']+=[i[1]] dic['max']+=[i[2]] from collections import defaultdict x = defaultdict(dict) for i in dic['day']: x[i]={'min':[],'max':[]} for i in range(len(dic['min'])): x[dic['day'][i]]['min']+=[dic['min'][i]] x[dic['day'][i]]['max']+=[dic['max'][i]] print(dict(x)) """ structure data for future use {'Friday 5 January': {'max': [0.83, 0.33], 'min': [6.48, 12.42]}, 'Thursday 4 January': {'max': [0.38, 0.73, 0.02], 'min': [11.58, 16.95, 23.68]}} """ result =[] for i in x: result.append(r'{}: {} meters at lowest an {} meters at highest'.format(i,min(x[i]['min']),max(x[i]['max']))) print(result) """output ['Thursday 4 January: 11.58 meters at lowest an 0.73 meters at highest', 'Friday 5 January: 6.48 meters at lowest an 0.83 meters at highest'] """"

--Set up some dummy data