4

我有一个表 color_balls 条目如下

=====================================================
Name    Red_Ball    Green_Ball  Yellow_Ball     
=====================================================
John       27           56          66
Mathew     37           45          15
=====================================================

我想编写一个 sql 或 mysql 查询来获得如下输出。

=====================================
Color_of_Balls      No_of_balls
=====================================
Red_Ball            64
Green_Ball          101
Yellow_Ball         81
=====================================
4

2 回答 2

4

这种类型的查询称为 UNPIVOT,不幸的是 MySQL 本身并不支持这种查询。但是,您可以使用 UNION 进行模拟:

SELECT 'Red_Ball' AS Color_of_Balls, SUM(Red_Ball) as No_of_Balls
FROM color_balls
UNION ALL
SELECT 'Green_Ball', SUM(Green_Ball)
FROM color_balls
UNION ALL
SELECT 'Yellow_Ball', SUM(Yellow_Ball)
FROM color_balls

Oracle10g 本身也不支持这个,虽然有这个解决方法

于 2013-02-06T19:19:18.607 回答
0

这应该适用于 Oracle 和 MySQL:

SELECT b.Color_of_Balls
     , CASE b.Color_of_Balls 
         WHEN 'Red_Ball'    THEN d.sum_red_ball
         WHEN 'Green_Ball'  THEN d.sum_green_ball
         WHEN 'Yellow_Ball' THEN d.sum_yellow_ball
       END AS No_of_balls
  FROM ( SELECT 'Red_Ball' AS Color_of_Balls FROM DUAL 
         UNION ALL SELECT 'Green_Ball' FROM DUAL
         UNION ALL SELECT 'Yellow_Ball' FROM DUAL
       ) b
 CROSS
  JOIN ( SELECT SUM(c.Red_Ball)    AS sum_red_ball
              , SUM(c.Green_Ball)  AS sum_green_ball
              , SUM(c.Yellow_Ball) AS sum_yellow_ball
           FROM color_balls c
       ) d
 ORDER
    BY CASE b.Color_of_Balls 
         WHEN 'Red_Ball'    THEN 1
         WHEN 'Green_Ball'  THEN 2
         WHEN 'Yellow_Ball' THEN 3
       END

请注意,这种方法只需要一次遍历color_balls表,而不是三次单独遍历表(或更多,取决于您需要返回多少行。)

于 2013-02-06T20:37:44.513 回答