简体   繁体   English

如何创建一个SQL选择,该选择将创建一个范围的所有数据并计算出现次数

[英]How to create a SQL select that creates all data for a range and counts occurences

I want to take data in one table that has records recording when events took place on certain dates and create output that has data for the complete date range with the number of events per person per date counted. 我想将数据收集在一个表中,该表具有记录在特定日期发生事件的记录,并创建具有完整日期范围数据的输出,其中包含每个日期每个人的事件数。

For example if I have a Source table containing data like this: 例如,如果我有一个包含这样的数据的Source表:

neil 01-05-2015
john 02-05-2015
neil 01-05-2015
neil 02-05-2015
jane 03-05-2015

A a second table containing all dates: 第二个表包含所有日期:

01-05-2015
02-05-2015
03-05-2015
04-05-2015

How can I combine them to create the desired output? 如何合并它们以创建所需的输出?

neil 01-05-2015 2
neil 02-05-2015 1
neil 03-05-2015 0
neil 04-05-2015 0
john 01-05-2015 0
john 02-05-2015 1
john 03-05-2015 0
john 04-05-2015 0
jane 01-05-2015 0
jane 02-05-2015 0
jane 03-05-2015 1
jane 04-05-2015 0

I have tried a variety of full joins but nothing seems to get me exactly what I need and I am wondering if it is possible in SQL alone. 我尝试了各种完全连接,但似乎没有什么能真正满足我的需要,我想知道仅在SQL中是否有可能。

Use a CROSS JOIN to first make a full cross-product between the dates and people. 使用CROSS JOIN首先在日期和人物之间进行完整的乘积CROSS JOIN Then use a LEFT JOIN to count all the matches. 然后使用LEFT JOIN来计算所有匹配项。

SELECT s1.name, d.date, IFNULL(COUNT(s2.name), 0)
FROM Dates AS d
CROSS JOIN (SELECT DISTINCT name FROM Source) AS s1
LEFT JOIN Source AS s2 ON s1.name = s2.name AND d.date = s2.date
GROUP BY s1.name, d.date

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM