选择:汇总值和按日期分组

时间:2018-11-07 23:32:16

标签: mysql sql date select

所以我的目标是求和并按日期分组。

起初,我只是用提供的日期写了它,但我需要以SUMYY-MM-DDYY-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
;

它看起来像这样:

And it looks like this

现在我已经了解到了:

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;

我明白了:

And i get this

所有...Concat(Round(SUM((ISNULL(Price.Morning,0) + ISNULL(Price.Day,0) + ISNULL(Price.Evening,0))*Tickets.Count),2),' €') AS 'Total'...是必需的,因为在数据库中有NULL个值,这就是为什么我使用ISNULL函数和0的原因,如果它是{{1} },因为否则将破坏所有计算。

您可以在此处看到该表:

This is the table with Prices

3 个答案:

答案 0 :(得分:1)

问题在于GROUP BY Date是按表中的Date列而不是别名Date进行分组。更改为:

GROUP BY DATE(Date)

答案 1 :(得分:0)

您可以使用Sub Macro1_Test_Hidden() ' ' Macro1_Test_Hidden Macro ' ' ' If Columns("BH:XFA").Hidden = False Then Columns("BH:XFA").Select Range("BH:XFA").Activate Selection.EntireColumn.Hidden = True Else Columns("BH:XFA").Select Range("BH:XFA").Activate Selection.EntireColumn.Hidden = False End If ' ' End Sub得到类似您想要的东西。没有任何样本数据,很难100%确定,但是此查询应该可以工作。请注意,您可以使用COALESCE来选择价格中的非NULL值,而不必在每个价格上都使用GROUP BY WITH ROLLUP

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

答案 2 :(得分:0)

修改了您的查询(将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;