我有两张桌子:
我想算一下特定客户的金额:
我希望将结果放在一栏中。
select c_id, count(*)
from orders o
join statuses s on o.o_nr = s.o_nr
where o.c_id in (1, 2)
?
group by o.c_id
详情:
订单
c_id | o_nr | pm
1 | 0004 | CC
1 | 0009 | CC
2 | 0011 | CC
2 | 0018 | installment
2 | 0020 | gift ;)
STATUSES
o_nr | status
0004 | shipped
0009 | in_progress
0011 | shipped
0018 | canceled
0020 | canceled
结果应为:
c_id | count (*)
1 | 1
2 | 3
答案 0 :(得分:1)
这是一种方法:
SELECT o.c_id
, COUNT(*)
FROM orders o
JOIN statuses s
ON s.o_nr = o.o_nr
AND ( (s.status = 'shipped' AND o.pm = 'CC')
OR (s.status = 'canceled' AND o.pm <> 'CC')
)
WHERE o.c_id in (1, 2)
GROUP BY o.c_id
对于这种类型的查询,我有时发现将条件测试移动到SELECT列表中的表达式是有利的。当我想返回0个计数时,这很有用,我想在多个“计数”中包含相同的行......
例如:
SELECT o.c_id
, SUM(s.status = 'shipped' AND o.pm = 'CC') AS shipped_and_cc
, SUM(s.status = 'canceled' AND o.pm <> 'CC') AS canceled_not_cc
, SUM((s.status = 'shipped' AND o.pm = 'CC')
OR (s.status = 'canceled' AND o.pm <> 'CC')) AS sac_and_cnc
, SUM(1) AS total_orders
FROM orders o
JOIN statuses s
ON s.o_nr = o.o_nr
WHERE o.c_id in (1, 2)
GROUP BY o.c_id