我遇到使用内部选择的问题,输出不太正确。任何帮助将不胜感激。
这是我的SQLFiddle示例。
这是我正在使用的查询。
SELECT
t.event as event_date,
count((
SELECT
count(s.id)
FROM mytable s
WHERE s.type = 2 AND s.event = event_date
)) AS type_count,
count((
SELECT
count(s.id)
FROM mytable s
WHERE s.type != 3 AND s.event = event_date
)) as non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event
我目前的输出:
October, 01 2013 00:00:00+0000 / 2 / 2
October, 03 2013 00:00:00+0000 / 1 / 1
The output I am trying to get:
October, 01 2013 00:00:00+0000 / 1 / 2
October, 03 2013 00:00:00+0000 / 0 / 0
因此,如果你看看我试图使用的查询,我基本上就是这样 尝试在日期范围内查询表,然后使用内部选择 获取与该类型匹配的行。 感谢您的帮助。
答案 0 :(得分:3)
可以简化一点并使用条件聚合排除子选择:
SELECT
t.event as event_date,
SUM(t.type = 2) AS type_count,
SUM(t.type != 3)AS non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event
演示:SQL Fiddle
这适用于MySQL,因为表达式返回1或0表示true / false。在其他数据库中,您可以通过SUM(CASE WHEN type=2 THEN 1 END)
答案 1 :(得分:1)
尝试这种方式:
SELECT
t.event as event_date,
SUM( case when type = 2 then 1 else 0 end )
AS type_count,
SUM( case when type != 3 then 1 else 0 end )
as non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event
演示: - &gt; http://sqlfiddle.com/#!2/19f3d/13
答案 2 :(得分:0)
您正在计算一个计数(count(select count(...
)。试试这个:
SELECT
t.event as event_date,
(SELECT
count(s.id)
FROM mytable s
WHERE s.type = 2 AND s.event = event_date
) AS type_count,
(SELECT
count(s.id)
FROM mytable s
WHERE s.type != 3 AND s.event = event_date
) as non_type_count
FROM mytable t
WHERE t.event >= '2013-10-01' AND t.event <= '2013-10-08'
GROUP BY t.event