Mysql 使用内部选择的查询计数

Mysql 使用内部选择的查询计数,mysql,sql,Mysql,Sql,在输出不太正确的地方使用内部选择时,我遇到了一个问题。任何帮助都将不胜感激 这是我的例子 这是我正在使用的查询 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)

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

这是我的例子

这是我正在使用的查询

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
所以,如果你看看我试图使用的查询,我基本上是 尝试查询日期范围内的表,然后使用内部选择 获取与类型匹配的行。 提前感谢您的帮助。

您正在计算计数选择计数。。。。试试这个:

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
您正在计数计数选择计数。。。。试试这个:

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

可以使用条件聚合简化位并排除子选择:

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
演示:


这在MySQL中有效,因为表达式返回1或0表示真/假。在其他数据库中,当type=2时,您可以通过SUMCASE实现相同的功能,然后1-END可以简化位并使用条件聚合排除子选择:

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
演示:

这在MySQL中有效,因为表达式返回1或0表示真/假。在其他数据库中,当type=2然后1 END时,您可以通过SUMCASE实现相同的功能。请尝试以下方法:

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
演示:->

尝试以下方法:

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

演示:->

感谢您提供SQL FIDLE,它使您可以非常轻松地加入并提供帮助+1感谢包含SQL FIDLE,让您可以轻松地加入并提供帮助+1.