-2

我有两个表名为

风格:

====================
   编号 | 风格
====================
    1 | X
====================
    2 | 是的

尺寸 :

============================================
   编号 | 尺寸名称 | style_id | 数量
============================================
    1 | 2T | 1 | 200
============================================
    2 | 3T | 1 | 100
============================================
    3 | 4T | 2 | 250
============================================
    4 | 2T | 2 | 500

使用这两个表我想要一个如下的报告:

==============================================
  风格 | 尺寸                      
==============================================
         | 2T | 3T | 4T |    
==============================================
   x | 200 | 100 | 0 |
==============================================
   是 | 500 | 0 | 250 |

提前致谢。请帮忙

4

2 回答 2

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 ║
╚══════╩═════╩═════╩═════╝

看到这个 SQLFiddle

于 2013-06-29T09:34:17.277 回答
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

演示在这里

于 2013-06-29T09:25:23.207 回答