sql查询产生以下结果

时间:2013-03-21 10:23:15

标签: mysql sql database oracle

  

任何人都可以告诉我在表格输出后会产生的SQL查询(MySQL)。

enter image description here

2 个答案:

答案 0 :(得分:1)

你正在寻找PIVOT TABLE QUERY - 尽管在(My)SQL中执行基本聚合通常更好,然后在应用程序级别处理显示问题(例如,使用一些PHP)。

标准查询可能如下所示,尽管MySQL支持与此标准的简写偏差......

SELECT DATE_FORMAT(date,'%M') month
     , COALESCE(SUM(CASE WHEN status = 'Rahul' THEN value END),0) Rahul 
     , COALESCE(SUM(CASE WHEN status = 'Vijay' THEN value END),0) Vijay
     , COALESCE(SUM(CASE WHEN status = 'Loki' THEN value END),0) Loki
  FROM my_table 
 GROUP 
    BY MONTH(date);

答案 1 :(得分:1)

WITH w AS (
  SELECT 10 AS value, 'Rahul' AS status, TO_DATE('20/01/2013', 'DD/MM/YYYY') AS date_time FROM dual
  UNION ALL
  SELECT 15, 'Vijay', TO_DATE('28/02/2013', 'DD/MM/YYYY') FROM dual
  UNION ALL
  SELECT 20, 'Loki', TO_DATE('03/02/2013', 'DD/MM/YYYY') FROM dual
  UNION ALL
  SELECT 25, 'Kiran', TO_DATE('05/01/2013', 'DD/MM/YYYY') FROM dual
  UNION ALL
  SELECT 5, 'Rahul', TO_DATE('02/01/2013', 'DD/MM/YYYY') FROM dual
  UNION ALL
  SELECT 15, 'Vijay', TO_DATE('10/01/2013', 'DD/MM/YYYY') FROM dual
  UNION ALL
  SELECT 08, 'Loki', TO_DATE('01/01/2013', 'DD/MM/YYYY') FROM dual
)
  SELECT TO_CHAR(date_time, 'Mon') AS m
         , SUM(CASE status WHEN 'Rahul' THEN value ELSE 0 END) AS Rahul
         , SUM(CASE status WHEN 'Vijay' THEN value ELSE 0 END) AS Vijay
         , SUM(CASE status WHEN 'Loki' THEN value ELSE 0 END) AS Loki
         , SUM(CASE status WHEN 'Kiran' THEN value ELSE 0 END) AS Kiran
         , SUM(value) AS Total
    FROM w
GROUP BY TO_CHAR(date_time, 'Mon')
ORDER BY TO_DATE(TO_CHAR(date_time, 'Mon'), 'Mon')
;