select:汇总值并按日期分组

ru9i0ody  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(332)

所以我的目标是总结我的价值观并按日期分组。
一开始我只是写了日期,但我需要提供 SUMYY-MM-DD , YY-MM 以及 YYYY 格式。

SELECT Table1.Date, Concat(Round(SUM((ISNULL(Price.Morning,0) + ISNULL(Price.Day,0) + ISNULL(Price.Evening,0))*Tickets.count),2),' €') AS 'Total' 
FROM Table1
JOIN Tickets ON Tickets.Table1_ID = Table1.Table1_ID
JOIN Price ON Tickets.Price_ID = Price.Price_ID 
GROUP BY Table1.Date
;

看起来是这样的:

现在我知道了:

SELECT Cast(Tabl1.Date as Date) AS 'Date', Concat(Round(SUM((ISNULL(Price.Morning,0) + ISNULL(Price.Day,0) + ISNULL(Price.Evening,0))*Tickets.Count),2),' €') AS 'Total'
FROM Table1
JOIN Tickets ON Tickets.Table1_ID = Table1.Table1_ID
JOIN Price ON Tickets.Price_ID = Price.Price_ID
GROUP BY Date;

我明白了:

所有的 ...Concat(Round(SUM((ISNULL(Price.Morning,0) + ISNULL(Price.Day,0) + ISNULL(Price.Evening,0))*Tickets.Count),2),' €') AS 'Total'... 因为在数据库中 NULL 价值观,这就是为什么我使用 ISNULL 功能和 0 万一是的话 NULL 因为否则它会破坏所有的计算。
你可以在这里看到那张表:

c9qzyr3d

c9qzyr3d1#

问题是 GROUP BY Date 是按 Date 列,而不是 Date 别名。更改为:

GROUP BY DATE(Date)
vcudknz3

vcudknz32#

修改了您的查询(将isnull更改为ifnull)并按日期分组为:

SELECT DATE(Table1.Date) myDate, Concat(Round(SUM((IFNULL(Price.Morning,0) + IFNULL(Price.Day,0) + IFNULL(Price.Evening,0))*Tickets.count),2),' €') AS 'Total' 
FROM Table1
JOIN Tickets ON Tickets.Table1_ID = Table1.Table1_ID
JOIN Price ON Tickets.Price_ID = Price.Price_ID 
GROUP BY myDate;
cx6n0qe3

cx6n0qe33#

你可以用电脑得到你想要的东西 GROUP BY WITH ROLLUP . 没有任何样本数据很难100%确定,但这个查询应该可以工作。请注意,您可以使用 COALESCE 选择价格中的非空值而不使用 IFNULL 在他们每个人身上。

SELECT YEAR(Table1.Date) AS year
     , MONTH(Table1.Date) AS month
     , DAY(Table1.Date) AS day
     , Round(SUM(COALESCE(Price.Morning, Price.Day, Price.Evening) * Tickets.count), 2) AS 'Total' 
FROM Table1
JOIN Tickets ON Tickets.Table1_ID = Table1.Table1_ID
JOIN Price ON Tickets.Price_ID = Price.Price_ID 
GROUP BY year, month, day WITH Rollup

这将为您提供一个如下所示的表:

year    month   day     Total
2017    7       24      476.00
2017    7       26      1992.20
2017    7       30      877.50
2017    7               3345.70
2017    8       2       2362.40
2017    8               2362.40
2017                    5708.10
                        5708.10

相关问题