以这样的方式加入两个表格,以便我可以获得所有日期的所有项目

时间:2012-11-27 19:41:58

标签: sql sql-server sql-server-2008-r2

我有两张桌子:购买和物品。对于Purchase表中的每个日期,我想查看Items表中每个项目购买的商品数量。下面是我期望从我的查询中得到的结果集。问题是如果某一天没有购买任何物品,则购买表中没有任何记录。日期必须来自购买表(没有连续日期)。

+-------------------------+----------+----------+
|      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)

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

除非您拥有包含所有日历日期的表格,或使用光标方法,否则您将无法填充未购买任何日期的日期。

答案 2 :(得分: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