![](/img/trans.png)
[英]Add another column on Dynamic Pivot Table and count the null/0 values
[英]Count values that exist in another table and pivot the result
我想從Chat
表中計算值:
ID REASON_ID DEPARTMENT_ID
1 46 1
2 46 1
3 50 1
4 50 2
5 100 1
6 100 2
那些存在於Reason
表中:
ID REASON_NAME
46 Reason1
50 Reason2
100 Reason3
DEPARTMENT_ID=1
,我想要這樣的結果:
ID46 ID50 ID100
2 1 1
我該怎么做?
您可以嘗試以下方法:
set @sql = null;
select group_concat( distinct
concat( ' sum(r.id= ', r.id,') as ID', r.id )
) into @sql
from Chat c
join Reason r on c.reason_id = r.id
where c.department_id = 1;
set @sql = concat('select ',@sql, '
from Chat c
join Reason r on c.reason_id = r.id
where c.department_id = 1');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
動態SQL解決方案更好,但如果您想要其他選項:
SELECT SUM(I46) ID46,
SUM(I50) ID50,
SUM(I100) ID100
FROM
(SELECT
COUNT(CASE WHEN reason_id = 46 THEN 1 END) I46,
COUNT(CASE WHEN reason_id = 50 THEN 1 END) I50,
COUNT(CASE WHEN reason_id = 100 THEN 1 END) I100
FROM chat
WHERE department_id = 1
GROUP BY reason_id) q1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.