我需要用每个日期的一列来报告我的数据。如果我需要提前指定日期(即,我不需要从表中的数据中发现日期),但每一列都必须包含该日期的数据。
我的源数据已标准化,因此每一行都有数据和日期。
例如,
create table test1 (
id int primary key,
name varchar(32),
created datetime default current_timestamp,
rows int
);
因此 test1 可能在行中包含日期
234 fred 2017-01-01 17
235 alice 2017-01-02 32
...
我正在寻找如下所示的输出:
NAME 2017-01-01 2017-01-02 2017-01-02
fred 17 19 24
alice 29 32 64
...
最佳答案
有效的方法(可能有更好的方法,但这个有效)是:
select name
, max(case when date(created) = '2017-12-01' then rows else 0 end) as '2017-12-01'
, max(case when date(created) = '2017-12-02' then rows else 0 end) as '2017-12-02'
, max(case when date(created) = '2017-12-03' then rows else 0 end) as '2017-12-03'
from test1
group by name;
case
将 created
的值按日期放入右侧列,否则放入零; max
清除零,以便 group by
显示所需的值。如果你不else 0
,你会得到NULLS,并且NULLS会淹没group by
中的值,并且它无法正常工作(经验之谈)。
关于mysql - 如何在 SQL (MySQL) 中按日期报告列中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47679748/