mysql 查询的自定义输出

Custom output from a mysql query

考虑以下架构:

    CREATE TABLE `Result` (
  `startDate` date NOT NULL,
  `description` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  `value` decimal(15,4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `Result`
(`startDate`,
`description`,
`value`)
VALUES
('2020-09-01' ,'Allowance' ,4000),
('2020-09-01' ,'Salary' ,1500),
('2020-10-01' ,'Allowance' ,2000),
('2020-10-01' ,'Salary' ,3000),
('2020-10-01' ,'Deduction' ,-200);

给定一个日期,结果应显示为描述和开始日期的总和以及所选日期与上一个日期(月份)之间的差异。因此,如果选择的月份是 10 月,则查询结果应显示为,

description SeptemberTotal OctoberTotal Variance
Allowance       4000         2000        -2000
Salary          1500         3000         1500 
Deduction       0            -200         -200

我尝试使用并集和枢轴,

SELECT @selectDate:='2020-10-01'; -- set desired date

SELECT 
    t.month,  
    t.description,
     Gross,
from (
    SELECT 
        DATE_FORMAT(pi.startDate, '%b/%y') AS 'Month',
        SUM(pi.value) AS gross,
        description
    FROM
        Result pi
    WHERE
        pi.startDate = DATE_SUB(@selectDate, INTERVAL 1 MONTH) -- select previous month
    GROUP BY description 
    UNION SELECT 
        DATE_FORMAT(pi.startDate, '%b/%y') AS 'Month',
        SUM(pi.value) AS gross,
        description
    FROM
        Result pi
    WHERE
        pi.startDate = @selectDate
    GROUP BY description) t
GROUP BY t.Month,t.description
;

结果为

Month   description   Gross
Sep/20  Allowance     4000
Sep/20  Salary        1500
Oct/20  Allowance     2000
Oct/20  Salary        3000
Oct/20  Deduction    -200

这不完全是要求。我也尝试过数据透视查询,但也没有按要求显示输出。

db-fiddle

SET @m1 := '2020-09-01';
SET @m2 := '2020-10-01';

SELECT Result.Description, 
       COALESCE(SUM(CASE WHEN Result.startDate = @m1 THEN value END), 0) Total1,
       COALESCE(SUM(CASE WHEN Result.startDate = @m2 THEN value END), 0) Total2,
       COALESCE(SUM(CASE WHEN Result.startDate = @m2 THEN value END), 0) -
       COALESCE(SUM(CASE WHEN Result.startDate = @m1 THEN value END), 0) Variance
FROM ( SELECT @m1 startDate UNION ALL SELECT @m2 ) baseDates
LEFT JOIN Result USING (startDate)
GROUP BY Result.Description

fiddle

select 描述,

sum(if(startDate between '2020-11-01 00:00:00' and '2020-11-31 23:59:59' ,value,0)) 1st,

sum(if(startDate between '2020-12-01 00:00:00' and '2020-12-31 23:59:59',value,0)) 第二,

sum(if(startDate between '2020-11-01 00:00:00' and '2020-11-31 23:59:59' ,value,0))-sum(if(created_at 在 '2020-12-01 00:00:00' 和 '2020-12-31 23:59:59' 之间,值,0)) 方差

来自 结果 其中“2020-11-01 00:00:00”和“2020-12-31 23:59:59”之间的开始日期按描述分组