1

使用 MySQL 查询,如何获取示例 A 中的表:

Example A
+------+---------------+----------+
| id   | value         | class    |
+------+---------------+----------+
| 1    | 33.00         | total    |
| 1    | 12.00         | shipping |
| 2    | 45.00         | total    |
| 2    | 15.00         | shipping |
+------+---------------+----------+

并创建一个类似于示例 B 的视图?

Example B
+------+---------------+---------------+
| id   | value_total   | value_shipping|
+------+---------------+---------------+
| 1    | 33.00         | 12.00         |
| 2    | 45.00         | 15.00         |
+------+---------------+---------------+
4

2 回答 2

0

试试这个

  select id , 
  max(case when class = 'total' then value end) as value_total
 , max(case when class = 'shipping' then value end) as value_shipping
  from Table1
  group by id

在这里演示

于 2013-05-06T11:27:36.037 回答
0

您可以简单地使用SUM()函数:

SELECT id
,SUM(CASE WHEN class = 'total' THEN value ELSE 0 END) AS value_total
,SUM(CASE WHEN class = 'shipping' THEN value ELSE 0 END) AS value_shipping
FROM Table1 
GROUP BY id;

看到这个 SQLFiddle

如果您的班级数量未知,请尝试此动态查询

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(case when class = ''',
      class,
      ''' then value else 0 end) AS `value_',
      class, '`'
    )
  ) INTO @sql
FROM Table1;


SET @sql = CONCAT('SELECT id, ', @sql, '
                  FROM Table1 
                  GROUP BY id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

输出:

╔════╦═════════════╦════════════════╗
║ ID ║ VALUE_TOTAL ║ VALUE_SHIPPING ║
╠════╬═════════════╬════════════════╣
║  1 ║          33 ║             12 ║
║  2 ║          45 ║             15 ║
╚════╩═════════════╩════════════════╝

看到这个 SQLFiddle

于 2013-05-06T11:29:45.777 回答