我有两张桌子:购买和物品。对于 Purchase 表中的每个日期,我想查看 Items 表中每个项目所购买的项目数。以下是我希望从查询中得到的结果集。问题是,如果某一天没有购买任何物品,那么 Purchase 表中就没有它的记录。日期必须来自采购表(无连续日期)。
+-------------------------+----------+----------+
| 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 |
+-------------------------+----------+----------+
什么样的查询会给我上面的结果和下面的数据?我正在使用 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)