我在mySQL
上有以下sqlfiddle
schema和查询。
基本上我正在尝试在每个日期间隔内获取count
个项目。
目前所有内容都按预期工作,但我发现我必须使用多个MySQL
查询才能检索所需的数据。
有没有办法将这些查询组合成任意数量的日期间隔?因此,在示例中,我有2个不同的查询来查询2个不同的日期间隔。我想知道是否可以在单个查询中查询3个或4个或更多个日期间隔?
答案 0 :(得分:0)
您使用conditional sum
作为
select
sum(
case when joined > '2014-01-01' and joined < '2014-06-30'
then 1 else 0 end
) as count1,
sum(
case when joined > '2014-07-01' and joined < '2014-12-31'
then 1 else 0 end
) as count2
from Users
答案 1 :(得分:0)
这很大程度上取决于你所说的“结合”:
一行
您可以使用Abhik's answer或类似的内容:
SELECT firstHalf.count, secondHalf.count
FROM
(SELECT COUNT(1) as count FROM Users WHERE joined BETWEEN '2014-01-01' AND '2014-06-30') firstHalf,
(SELECT COUNT(1) as count FROM Users WHERE joined BETWEEN '2014-07-01' AND '2014-12-31') secondHalf;
多行
您可以使用UNION ALL
同时运行查询并合并结果:
SELECT * FROM
(SELECT COUNT(1) as count FROM Users WHERE joined BETWEEN '2014-01-01' AND '2014-06-30') firstHalf
UNION ALL
(SELECT COUNT(1) as count FROM Users WHERE joined BETWEEN '2014-07-01' AND '2014-12-31') secondHalf;
您没有提出的问题
听起来你想得到半任意日期范围的计数。这就是GROUP BY
与MySQL Date Operations相结合的含义。这将检索自2010年初以来加入的所有用户的计数,按年份分组,以及他们注册的年份的一半(0或1)。
SELECT YEAR(joined) as year, MONTH(joined) / 6 AS yearHalf, COUNT(*)
FROM Users
WHERE joined >= '2010-01-01'
GROUP BY YEAR(joined), MONTH(joined) / 6;
使用上面的查询格式,您可以轻松更改计算的细微程度,是否按年份分组等。