说我有这样的表
ID, SN, USED
002, 183000153206, 0
002, 180000205206, 0
002, 188000373206, 0
002, 186000495206, 0
002, 181000521206, 0
001, 180000107106, 0
001, 181000206106, 0
001, 182000337106, 0
001, 180000453106, 1
001, 188000557106, 0
001, 184000639106, 0
我想计算每个ID的SN使用计数,如果我的SQL脚本是正确的,结果可能是:
ID, USED_Count
002, 0
001, 1
这是我到目前为止所做的,但它只显示ID 001记录,没有ID 002。
select id, count(sn) as sums
from sn_table
where sn is not null
and used is not null
group by id
--having sums >= 0
我知道使用的条件不是空似乎不对,但我在这里放了几个小时,我怎么能这样做?
答案 0 :(得分:3)
您可以使用简单的SUM
:
select id, SUM(used) as sums
from sn_table
group by id
order by id desc;
或条件聚合:
SELECT id, COUNT(DISTINCT CASE WHEN used = 1 THEN sn END) AS USED_COUNT
FROM sn_table
GROUP BY id;
<强> DBFiddle Demo 强>
答案 1 :(得分:0)
目前尚不清楚您尝试实施的逻辑。也许你只想计算每列的不同出现次数?
select id
, count(distinct sn) as sn_cnt
, count(distinct used) as used_cnt
from sn_table
where sn is not null
and used is not null
group by id