简体   繁体   中英

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:

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.

Use a CROSS JOIN to first make a full cross-product between the dates and people. Then use a LEFT JOIN to count all the matches.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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