SQL 统计组数

SQL count number of groups

我有一个 table 托盘、物品、物品数量:

pallet | item | qty
-------------------
  1        1     2
  1        2     4
  2        3     2
  2        5     3
  3        4     4

我需要找到 count(pallet)、count(item)、sum(qty)

count(pallets) | count(items) | sum(qty)
----------------------------------------
      3                5           15

我可以用

得到 sum(qty) 和 count(item)
select count(0) as totalItems, sum(qty) as total from table

有没有不用子查询就可以得到托盘数量的方法?

是,使用DISTINCT

select count(distinct pallet) as pallets,
       sum(qty) as total, 
       count(*) as totalItems 
from your_table

只需使用 Distinct 即可避免重复记录被统计。

count(Distinct pallet)

你的查询是这样的

select 
      count(distinct pallet) as pallets,
      sum(qty) as Total, 
      count(item) AS [Total Items]

它将给出输出 AS :