我有两个名为
的表式:
=================== id | style =================== 1 | x =================== 2 | y
尺寸:
=========================================== id | size_name | style_id | Quantity =========================================== 1 | 2T | 1 | 200 =========================================== 2 | 3T | 1 | 100 =========================================== 3 | 4T | 2 | 250 =========================================== 4 | 2T | 2 | 500
使用这两个表我想要一个如下的报告:
============================================= Style | size ============================================= | 2T | 3T | 4T | ============================================= x | 200 | 100 | 0 | ============================================= y | 500 | 0 | 250 |
提前致谢。请帮忙
答案 0 :(得分:1)
静态查询(如果已知且数量有限的size_name)
SELECT st.Style
,SUM(CASE WHEN s.size_name = '2T' THEN Quantity ELSE 0 END) AS `2T`
,SUM(CASE WHEN s.size_name = '3T' THEN Quantity ELSE 0 END) AS `3T`
,SUM(CASE WHEN s.size_name = '4T' THEN Quantity ELSE 0 END) AS `4T`
FROM Size s
JOIN Style st ON s.style_id = st.id
GROUP BY st.Style;
动态查询(如果您不知道size_name的数量)
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(CASE WHEN `size_name` = ''',
`size_name`,
''' THEN Quantity ELSE 0 END) AS `',
`size_name`, '`'
)
) INTO @sql
FROM Size;
SET @sql = CONCAT('SELECT st.Style , ', @sql, '
FROM Size s
JOIN Style st ON s.style_id = st.id
GROUP BY st.Style
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
输出:
╔══════╦═════╦═════╦═════╗
║ TYLE ║ 2T ║ 3T ║ 4T ║
╠══════╬═════╬═════╬═════╣
║ x ║ 200 ║ 100 ║ 0 ║
║ y ║ 500 ║ 0 ║ 250 ║
╚══════╩═════╩═════╩═════╝
答案 1 :(得分:0)
试试这个
select
style ,
max(case when size_name = '2T' then Quantity else 0 end) as '2T' ,
max(case when size_name = '3T' then Quantity else 0 end) as '3T' ,
max(case when size_name = '4T' then Quantity else 0 end) as '4T'
from style inner join size
on size.style_id = style.id
group by style.id