有6种票类型。用户将输入开始日期和结束日期。然后我必须显示这两个日期之间每天有多少种类的门票。
票证表: id(int),type_id(int),created_at(日期)和更多字段
输入: date_begin,date_end
输出行>日期。列> date,total_amount和每种类型
我当前的查询:
SELECT
DATE(ticket.created_date) as date,
SUM(IF(ticket.created_date, 1, 0)) as total,
SUM(IF(ticket.type_id is Null, 1, 0)) as total0,
SUM(IF(ticket.type_id = 1, 1, 0)) as total1,
SUM(IF(ticket.type_id = 2, 1, 0)) as total2,
SUM(IF(ticket.type_id = 3, 1, 0)) as total3,
SUM(IF(ticket.type_id = 4, 1, 0)) as total4,
SUM(IF(ticket.type_id = 5, 1, 0)) as total5
FROM
ticket
JOIN
ticket_type ON ticket_type.id = ticket.type_id
WHERE
DATE(ticket.created_date) BETWEEN '2015-06-12' AND '2015-06-22'
GROUP BY
DATE(ticket.created_date)
当前输出:
期望的输出:
如您所见,今天是2015-06-19。所以我的数据库目前只有数据,直到现在(今天)。但是如果用户的end_date是将来的,我希望在那天之前获取行,数据将为0。
答案 0 :(得分:1)
首先,你必须创建功能“explodeDates”。你在我之前的评论链接上有一个定义的例子。但是,如果您使用的是SqlServer,则可以使用以下代码:
CREATE FUNCTION explodeDates(@firstDate DATE, @secondDate DATE)
RETURNS
@mytable TABLE
(
mydate DATE
)
AS
BEGIN
WHILE @firstDate < @secondDate
BEGIN
INSERT INTO @mytable(mydate) VALUES (@firstDate);
SET @firstDate = DATEADD(day, 1, @firstdate);
END
RETURN
END
GO
当您定义了该功能时,可以这样调用它:
SELECT * FROM dbo.explodeDates('01/01/2015', '31/01/2015')
之后,您只需要像这样定义初始查询:
SELECT
d.mydate as date,
SUM(IF(ticket.created_date, 1, 0)) as total,
SUM(IF(ticket.type_id is Null, 1, 0)) as total0,
SUM(IF(ticket.type_id = 1, 1, 0)) as total1,
SUM(IF(ticket.type_id = 2, 1, 0)) as total2,
SUM(IF(ticket.type_id = 3, 1, 0)) as total3,
SUM(IF(ticket.type_id = 4, 1, 0)) as total4,
SUM(IF(ticket.type_id = 5, 1, 0)) as total5
FROM
dbo.explodeDates('12/06/2015', '22/06/2015') d
LEFT JOIN ticket t ON t.created_date = d.mydate
LEFT JOIN ticket_type ON ticket_type.id = ticket.type_id
GROUP BY
d.mydate
答案 1 :(得分:0)
首先,必须在前面验证。此外,如果有这样的查询,我认为你的输出是有效的。如何显示未来日期的门票(未创建)。我认为这些不是电影票..:P