为行组添加总量列

Rob*_*ert 3 sql-server aggregate sql-server-2012 window-functions

我有一个 Items 表和一个 Inventory 表。一个项目可以属于多个库存记录。我正在尝试返回所有库存记录的列表,但在新列中包含它们的数量。例如:

项目

ItemID     ItemDescription
103        Headphones
115        Speakers
230        Wireless Adapter
275        20' Network Cable
Run Code Online (Sandbox Code Playgroud)

存货

InventoryID        ItemID        WarrantyDate       Status
1                  103           12/22/2010         Available
2                  103           05/15/2012         Available
3                  103           02/24/2015
4                  275           01/01/2010
5                  275           01/01/2011
Run Code Online (Sandbox Code Playgroud)

如果我尝试COUNT使用 ItemID 和GROUP BYItemID,如下所示:

SELECT ItemID, COUNT(ItemID) AS Quantity
FROM Inventory
GROUP BY ItemID
Run Code Online (Sandbox Code Playgroud)

我得到:

ItemID  Quantity
103     3
275     2        
Run Code Online (Sandbox Code Playgroud)

但我真正想要的是:

InventoryID        ItemID        WarrantyDate       Status       Quantity
1                  103           12/22/2010         Available    3
2                  103           05/15/2012         Available    3
3                  103           02/24/2015                      3
4                  275           01/01/2010                      2
5                  275           01/01/2011                      2
Run Code Online (Sandbox Code Playgroud)

任何建议/想法表示赞赏。

spa*_*dba 7

您可以使用函数OVER上的子句COUNT来获取所需内容:

CREATE TABLE #inventory(
   InventoryID  INTEGER  NOT NULL PRIMARY KEY 
  ,ItemID       INTEGER  NOT NULL
  ,WarrantyDate DATE  NOT NULL
  ,Status       VARCHAR(9)
);
INSERT INTO #inventory(InventoryID,ItemID,WarrantyDate,Status) VALUES (1,103,'12/22/2010','Available');
INSERT INTO #inventory(InventoryID,ItemID,WarrantyDate,Status) VALUES (2,103,'05/15/2012','Available');
INSERT INTO #inventory(InventoryID,ItemID,WarrantyDate,Status) VALUES (3,103,'02/24/2015',NULL);
INSERT INTO #inventory(InventoryID,ItemID,WarrantyDate,Status) VALUES (4,275,'01/01/2010',NULL);
INSERT INTO #inventory(InventoryID,ItemID,WarrantyDate,Status) VALUES (5,275,'01/01/2011',NULL);

SELECT *, COUNT(ItemID) OVER (PARTITION BY ItemID) AS Quantity
FROM #Inventory
Run Code Online (Sandbox Code Playgroud)

输出:

+-------------+--------+--------------+-----------+----------+
| InventoryID | ItemID | WarrantyDate |  Status   | Quantity |
+-------------+--------+--------------+-----------+----------+
|           1 |    103 | 2010-12-22   | Available |        3 |
|           2 |    103 | 2012-05-15   | Available |        3 |
|           3 |    103 | 2015-02-24   | NULL      |        3 |
|           4 |    275 | 2010-01-01   | NULL      |        2 |
|           5 |    275 | 2011-01-01   | NULL      |        2 |
+-------------+--------+--------------+-----------+----------+
Run Code Online (Sandbox Code Playgroud)