0

我有两张桌子:购买和物品。对于 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)
4

3 回答 3

2

您可以从 Purchase 表中交叉加入一组不同的日期以获取您的日期列表。如果在特定日期至少购买了一件商品,这只会返回一个日期:

SELECT
 dt.PurchaseDate, i.Value as ItemName, SUM(ISNULL(Quantity,0)) as Quantity
FROM Items i
CROSS JOIN ( SELECT DISTINCT PurchaseDate FROM Purchase ) dt
LEFT OUTER JOIN Purchase p
  ON i.Value = p.ItemName
  AND dt.PurchaseDate = p.PurchaseDate
GROUP BY dt.PurchaseDate, i.Value
ORDER BY dt.PurchaseDate, i.Value
于 2012-11-27T19:52:12.563 回答
1

除非您有一个包含所有日历日期的表格,或者使用游标方法,否则您将无法填充没有购买任何东西的日期。

于 2012-11-27T19:53:03.877 回答
0
select
    p.purchasedate,
    i.value,
    sum(case when p.itemname = i.value then p.quantity else 0 end)
from
    Purchase p
    cross join Items i
group by
    p.purchasedate,
    i.value
order by
    p.purchasedate, 
    i.value
于 2012-11-27T19:59:23.773 回答