我有一个存储admin_id
和comment
的表格,我正在尝试查询它以获取与每个管理员相关的不同评论的计数。
我试图这样做:
select admin_id,
count(comment like 'Approved the claim for%') as Approved,
count(comment like 'Rejected the claim for%') as Rejected,
count(comment like 'Temporarily rejected (24 hour hold) the claim for%') as TempReject,
count(comment like 'Permanently rejected the claim for%') as PermReject
from admin_comments
group by admin_id
然而,这会产生结果,其中列Approved
,Rejected
,TempReject
和PermReject
都是相同的,以及顶部的一行似乎是在admin_id
为NULL
的所有位置汇总它们:
我需要在查询中更改哪些内容才能获得按admin_id
分组的每种评论类型的准确数据。
答案 0 :(得分:1)
试试这个:出于此目的使用CASE表达式
select admin_id,
SUM(CASE WHEN comment like 'Approved the claim for%' THEN 1 ELSE 0 END) as Approved,
SUM(CASE WHEN comment like 'Rejected the claim for%' THEN 1 ELSE 0 END) as Rejected,
SUM(CASE WHEN comment like 'Temporarily rejected (24 hour hold) the claim for%' THEN 1 ELSE 0 END) as TempReject,
SUM(CASE WHEN comment like 'Permanently rejected the claim for%' THEN 1 ELSE 0 END ) as PermReject
from admin_comments
group by admin_id
答案 1 :(得分:1)
COUNT不执行布尔表达式,因此您无法在COUNT中使用LIKE。你必须使用CASE / WHEN
select admin_id,
count( WHEN comment like 'Approved the claim for%' THEN 1 ELSE NULL END) as Approved,
count(WHEN comment like 'Rejected the claim for%' THEN 1 ELSE NULL END) ....
请注意,它必须为NULL而不是0,因为COUNT计算非空值。 O是非空值
答案 2 :(得分:1)
select admin_id,
count(case when comment like 'Approved the claim for%' then 1 else null end) as Approved,
count(case when comment like 'Rejected the claim for%' then 1 else null end) as Rejected,
count(case when comment like 'Temporarily rejected (24 hour hold) the claim for%' then 1 else null end) as TempReject,
count(case when comment like 'Permanently rejected the claim for%' then 1 else null end ) as PermReject
from admin_comments
group by admin_id