怎么从查询中获取TOP?

时间:2016-04-01 13:43:04

标签: mysql

SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id

如何从此查询中获取具有最大计数TOP 100的行type = 'yes'

3 个答案:

答案 0 :(得分:1)

您可以使用LIMIT来限制结果数量,并使用ORDER BY对其进行排序,以便结果按总计的降序排列。

SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id
ORDER BY type_1 DESC
LIMIT 100

答案 1 :(得分:0)

您应该在查询中添加WHERE语句以添加条件语句 另外,我可以看到你正在使用mysql,这意味着你应该通过参数降序排序数据并将结果限制为100

    SELECT
        user_id,
        count(*) total,
        sum(case when type = 'yes' then 1 else 0 end) as type_1,
        sum(case when type = 'no' then 1 else 0 end) as type_2
    FROM history
    WHERE type='yes'
    GROUP by user_id
    ORDER BY total DESC
    LIMIT 100 

答案 2 :(得分:0)

SELECT
    user_id,
    count(*) total,
    sum(case when type = 'yes' then 1 else 0 end) as type_1,
    sum(case when type = 'no' then 1 else 0 end) as type_2
FROM history
GROUP by user_id
ORDER by type_1 DESC
LIMIT 100