计算另一个 table 中存在的值并旋转结果
Count values that exist in another table and pivot the result
我想计算 个来自Chat
table 的值:
ID REASON_ID DEPARTMENT_ID
1 46 1
2 46 1
3 50 1
4 50 2
5 100 1
6 100 2
那些存在于 Reason
table :
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;
我想计算 个来自Chat
table 的值:
ID REASON_ID DEPARTMENT_ID
1 46 1
2 46 1
3 50 1
4 50 2
5 100 1
6 100 2
那些存在于 Reason
table :
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;