所以我目前有下表:
REF| STATUS
OP1|0
OP2|2
OP2|4
OP2|5
OP3|7
OP3|6
如您所见,OP2有3个雕像,OP3有2个状态。 我试图归档以下内容:
REF| STATUS | COUNT
OP1|0 |1
OP2|2 |3
OP2|4 |3
OP2|5 |3
OP3|7 |2
OP3|6 |2
计算每个参考的状态数。
我提供了一个SQL,但不确定我的错误是什么?
SELECT ref,STATUS, (SELECT COUNT(STATUS) FROM orders WHERE STATUS > 0 GROUP BY ref)
FROM orders
我正在使用SQL Server 2008。
答案 0 :(得分:6)
使用COUNT() OVER()
SELECT ref,STATUS, COUNT(*) OVER(PARTITION BY REF1)
FROM orders
获取状态>的计数0,上面的查询可以改为
SELECT ref,STATUS, COUNT(CASE WHEN STATUS>0 THEN 1 END) OVER(PARTITION BY REF1)
FROM orders
答案 1 :(得分:1)
使用相关子查询:
select ref
, status
, (
select count(i.status)
from orders i
where i.status > 0
and i.ref = o.ref
) as OrderCount
from orders o
inner join
可能会更有效率:
select
o.ref
, o.status
, i.OrderCount
from orders o
left join (
select
ref
, count(i.status) as OrderCount
from orders i
where i.status > 0
group by ref
) i
on i.ref = o.ref