I’ve two tables: purchase and items. For every date in the Purchase table, I’d like to see the number of items purchased for every single items in the Items table. Below is the result set I would expect from my query. The issue is that if no items were purchased for a given day, there’s no record of it in the Purchase table. The dates must be coming from the Purchase table (no continuous dates).
+-------------------------+----------+----------+
| PurchaseDate | ItemName | Quantity |
+-------------------------+----------+----------+
| 2000-01-01 00:00:00.000 | A | 1 |
| 2000-01-01 00:00:00.000 | B | 2 |
| 2000-01-01 00:00:00.000 | C | 4 |
| 2000-01-04 00:00:00.000 | A | 6 |
| 2000-01-04 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase
| 2000-01-04 00:00:00.000 | C | 0 | <- This row doesn't exist in Purchase
| 2000-01-07 00:00:00.000 | A | 0 | <- This row doesn't exist in Purchase
| 2000-01-07 00:00:00.000 | B | 0 | <- This row doesn't exist in Purchase
| 2000-01-07 00:00:00.000 | C | 3 |
+-------------------------+----------+----------+
What kind a query would give me the result above with the data below? I am using SQL Server 2008 R2.
CREATE TABLE Purchase
(
PurchaseDate DATETIME,
ItemName NVARCHAR(200),
Quantity INT
)
CREATE TABLE Items
(
Value NVARCHAR(200)
)
INSERT INTO Items VALUES ('A')
INSERT INTO Items VALUES ('B')
INSERT INTO Items VALUES ('C')
INSERT INTO Purchase VALUES ('2000-01-01', 'A', 1)
INSERT INTO Purchase VALUES ('2000-01-01', 'B', 2)
INSERT INTO Purchase VALUES ('2000-01-01', 'C', 4)
INSERT INTO Purchase VALUES ('2000-01-04', 'A', 6)
INSERT INTO Purchase VALUES ('2000-01-07', 'C', 3)
You can cross join a distinct set of dates from the Purchase table to get your list of dates. This will only return a date if at least one item was purchased on a particular date: