如何在 sql server 2008 R2 的一个查询中 运行 distinct 和 Sum
How to run distinct and Sum in one query in sql server 2008 R2
我有一个 table #1,如附图所示。首先,我想对所有不同 ID 的所有数量求和。然后要显示具有相同数量的 id 的数量。
使用SUM
和COUNT
:
SELECT
COUNT(*) AS totalId,
qty
FROM (
SELECT
id, SUM(qty) AS qty
FROM tbl
GROUP BY id
)t
GROUP BY qty
显示所有不同 ID 的所有数量的总和:
SELECT id,SUM(qty) FROM table GROUP BY id;
显示数量相同的id
SELECT count(id),quantity FROM (SELECT id,SUM(qty) AS quantity FROM table GROUP BY id) GROUP BY quantity
创建临时文件后试试这个 table
create table #Temp
(
id int,
qty int
)
Insert Into #Temp
SELECT id, SUM(qty)
FROM yourTable
group by id
SELECT * FROM #Temp
SELECT Count(id) , qty
FROM #Temp
GROUP BY qty
ORDER BY qty DESC
我有一个 table #1,如附图所示。首先,我想对所有不同 ID 的所有数量求和。然后要显示具有相同数量的 id 的数量。
使用SUM
和COUNT
:
SELECT
COUNT(*) AS totalId,
qty
FROM (
SELECT
id, SUM(qty) AS qty
FROM tbl
GROUP BY id
)t
GROUP BY qty
显示所有不同 ID 的所有数量的总和:
SELECT id,SUM(qty) FROM table GROUP BY id;
显示数量相同的id
SELECT count(id),quantity FROM (SELECT id,SUM(qty) AS quantity FROM table GROUP BY id) GROUP BY quantity
创建临时文件后试试这个 table
create table #Temp
(
id int,
qty int
)
Insert Into #Temp
SELECT id, SUM(qty)
FROM yourTable
group by id
SELECT * FROM #Temp
SELECT Count(id) , qty
FROM #Temp
GROUP BY qty
ORDER BY qty DESC