加入三个表并计算
表部
mid m_name
1 Health
2 Telecom
3 Economic
表DocumentDetail
id m_id doc_type
1 3 1
2 1 2
3 2 3
4 3 2
5 2 4
6 3 1
表类型:
dID d_name
1 pdf
2 xls
3 doc
4 png
5 zip
我想像这样放
m_name pdf xls doc png zip
health 0 1 0 0 0
Telecom 0 0 1 1 0
Economic 2 1 0 0 0
我们可以像这样查询输出吗?提前谢谢。
答案 0 :(得分:0)
SELECT m_name,(SUM(CASE doc_type WHEN 1 THEN 1 ELSE 0 END)) as pdf,
(SUM(CASE doc_type WHEN 2 THEN 1 ELSE 0 END)) AS xls,
(SUM(CASE doc_type WHEN 3 THEN 1 ELSE 0 END)) AS doc,
(SUM(CASE doc_type WHEN 4 THEN 1 ELSE 0 END)) AS png,
(SUM(CASE doc_type WHEN 5 THEN 1 ELSE 0 END)) AS zip
FROM Ministry INNER JOIN DocumentDetail ON Ministry.`mid` = DocumentDetail.`m_id`
GROUP BY m_name
点击此SQL Fiddle 希望这有帮助
答案 1 :(得分:0)
如果doc_type
的数量是固定的,那么您可以尝试以下查询,否则您可能需要尝试动态SQL查询。
<强>查询强>
select t1.m_name,
count(case t2.doc_type when 1 then 1 end) as pdf,
count(case t2.doc_type when 2 then 1 end) as xls,
count(case t2.doc_type when 3 then 1 end) as doc,
count(case t2.doc_type when 4 then 1 end) as png,
count(case t2.doc_type when 5 then 1 end) as zip
from Ministry t1
join DocumentDetail t2
on t1.mid = t2.m_id
group by t1.m_name;
答案 2 :(得分:0)
如果类型的数量会随着时间的推移而变化,请使用此解决方案:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
', SUM(CASE dd.doc_type when ', dID,
' then 1 else 0 END) AS ', d_name, ' ')
SEPARATOR '') INTO @sql
FROM Type;
SET @sql = CONCAT(
'SELECT m.m_name',
@sql,
'FROM
Ministry AS m
INNER JOIN DocumentDetail AS dd ON (m.mid = dd.m_id)
GROUP BY m.m_name
ORDER BY m.m_name'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
m_name pdf xls doc png zip
Economic 2 1 0 0 0
Health 0 1 0 0 0
Telecom 0 0 1 1 0