如何计算同一列中不同where子句的值?

时间:2017-01-05 17:54:38

标签: mysql sql count grouping medoo

我讨厌我不得不问,但我无法处理它。

我有这张表votes

enter image description here

type=1是一个upvote,type=0将是一个downvote

我想要这个输出:

[
  {'video': 'best-of-mehrwert', 'upvote': 2, 'downvote': 0},
  {...}
]

我正在使用medoo:

<?php
$votes = $database->query(
  // 'SELECT COUNT(video) as votes, video FROM votes GROUP BY video, type'
  '
    SELECT video,COUNT(*) as counts
    FROM votes
    GROUP BY video,type;

  '
)->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($votes);

给了我

[{"video":"anlaesse","counts":"1"},{"video":"best-of-mehrwert","counts":"2"}]

如何“添加列”,如“upvotes”,即type = 1且type = 0的条目?

3 个答案:

答案 0 :(得分:2)

两种变体:

select
  video,
  sum(case when type=1 then 1 else 0 end) as upvote,
  sum(case when type=0 then 1 else 0 end) as downvote
from votes
group by video

select
  video,
  sum(type) as upvote,
  sum(1-type) as downvote
from votes
group by video

http://www.sqlfiddle.com/#!9/c73f2a/5

答案 1 :(得分:1)

我认为,对于您的条件匹配的每一行,SUM最多为1可能是最简单的:

SELECT 
    video, 
    SUM(CASE type WHEN 1 THEN 1 ELSE 0 END) as upvotes,
    SUM(CASE type WHEN 0 THEN 1 ELSE 0 END) as downvotes 
FROM 
    votes
GROUP BY 
    video;

注意,您应该忽略type中的GROUP BY,以便为每个视频获得一行。

答案 2 :(得分:0)

您可以使用case表达式仅计算您感兴趣的投票类型:

SELECT   video, 
         COUNT(CASE type WHEN 1 THEN 1 END) as upvotes
         COUNT(CASE type WHEN 0 THEN 1 END) as downvotes
FROM     votes
GROUP BY video, type;