【问题标题】:Select Count From 1 Column Into 2 Columns选择从 1 列计数到 2 列
【发布时间】:2013-01-01 11:51:16
【问题描述】:

我有一个表,有一个名为 type 的列,它包含两个词之一 upvotedownvote 我想按 a.question_id 分组,然后得到 2 列,每列计数。

select a.*, u.* from answers a
left join users u using(user_id)
left join vote_history v using(answer_id)
where a.question_id = 4 and deleted < 4
group by v.question_id
order by votes desc

示例选择

ColumnA  | ColumnB  | upvotes | downvotes
---------+----------+---------+----------
record1A | record2B | 3       | 2
record2A | record2B | 2       | 5

我是否可以在不执行多个查询且不执行子查询的情况下执行此操作?

【问题讨论】:

    标签: mysql select join count group-by


    【解决方案1】:

    这被称为枢轴。在 MySQL 中,您可以使用带有 CASE 表达式的聚合函数将数据转换为列:

    select a.*, u.*,
        SUM(case when v.type='upvote' then 1 else 0 end) Upvotes,
        SUM(case when v.type='downvote' then 1 else 0 end) Downvotes,
    from answers a
    left join users u using(user_id)
    left join vote_history v using(answer_id)
    where a.question_id = 4 and deleted < 4
    group by v.question_id
    order by votes desc
    

    【讨论】:

      【解决方案2】:

      这一切都有效:

      select 
        a.*, 
        u.*,
        SUM(IF(v.type = 'upvote',1,0) as upvotes,
        SUM(IF(v.type = 'downvote',1,0) as downvotes,
      from answers a
      left join users u using(user_id)
      left join vote_history v using(answer_id)
      where a.question_id = 4 and deleted < 4
      group by v.question_id
      order by votes desc
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2012-11-03
        • 2011-03-27
        • 2012-11-05
        • 1970-01-01
        • 2015-07-17
        • 1970-01-01
        相关资源
        最近更新 更多