我有表Inventory,我想sum(quantity)
按列 gid、版本、仓库分组
+----------+----------+-----------+----------+--------------+
| gid | version | warehouse| quantity | description |
+----------+----------+-----------+----------+--------------+
| gid1 + 1 + 1 + 100 + name 1 +
| gid1 + 1 + 1 + 200 + name 1 +
| gid2 + 1 + 2 + 200 + name 2 +
+----------+----------+-----------+----------+--------------+
以下查询有效,因为它返回 2 条记录的总和:
SELECT gid, version, warehouse, SUM(quantity) as total
FROM Inventory
GROUP BY gid, version, warehouse;
+----------+----------+-----------+----------+
| gid | version | warehouse| quantity |
+----------+----------+-----------+----------+
| gid1 + 1 + 1 + 300 +
| gid2 + 1 + 2 + 200 +
+----------+----------+-----------+----------+
我还尝试description
在记录中添加该列:
SELECT gid, version, warehouse, SUM(quantity) as total, description
FROM Inventory
GROUP BY gid, version, warehouse;
但我收到一条错误消息:
列“描述”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中
我搜索了它,最后得到了这个查询:
SELECT T1.gid
,T1.description
,T1.version
,T1.warehouse
,T2.quantity
FROM Inventory T1
INNER JOIN (
SELECT gid, version, warehouse, SUM(quantity) AS quantity
FROM Inventory
GROUP BY gid, version, warehouse
) T2
ON T1.gid = T2.gid
它显示了正确的总和,但它返回 3 条记录:
+----------+----------+-----------+----------+--------------+
| gid | version | warehouse| quantity | description |
+----------+----------+-----------+----------+--------------+
| gid1 + 1 + 1 + 300 + name 1 +
| gid1 + 1 + 1 + 300 + name 2 +
| gid2 + 1 + 2 + 200 + name 2 +
+----------+----------+-----------+----------+--------------+
我怎样才能只得到 2 个箭头?以下是所需的输出:
+----------+----------+-----------+----------+--------------+
| gid | version | warehouse| quantity | description |
+----------+----------+-----------+----------+--------------+
| gid1 + 1 + 1 + 300 + name 1 +
| gid2 + 1 + 2 + 200 + name 2 +
+----------+----------+-----------+----------+--------------+
我的数据库在 SQL Server Express 2008 中。