2

我在使用输出不太正确的内部选择时遇到问题。任何帮助将不胜感激。

这是我的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

因此,如果您查看我尝试使用的查询,我基本上是在尝试查询日期范围内的表,然后使用内部选择获取与类型匹配的行。提前感谢您的帮助。

4

3 回答 3

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 小提琴

这在 MySQL 中有效,因为表达式返回 1 或 0 表示真/假。在其他数据库中,您可以通过SUM(CASE WHEN type=2 THEN 1 END)

于 2013-10-23T19:18:29.310 回答
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

演示:--> http://sqlfiddle.com/#!2/19f3d/13

于 2013-10-23T19:21:16.917 回答
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
于 2013-10-23T19:17:43.640 回答