-2

谁能告诉我 sql 查询(MySQL)将导致表中的输出。

在此处输入图像描述

4

2 回答 2

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')
;
于 2013-03-21T10:50:51.617 回答
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);
于 2013-03-21T10:46:18.543 回答