如何计算同一列上具有不同 where 子句的值?

How to count values with different where clauses on the same column?

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

我有这个 table votes:

type=1 是赞成票,type=0 是反对票

我想要这个输出:

[
  {'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"}]

我如何 "add a column" 喜欢 "upvotes" 即 type = 1 和 type = 0 相同的条目?

我认为最简单的方法是 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;

请注意,您应该从 GROUP BY 中省略 type,以便为每个视频返回一行。

您可以使用 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;

两种变体:

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