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

1.4k views Asked by At

I hate that I have to ask but I just cant handle it.

I have this table votes:

enter image description here

type=1 is an upvote, type=0 would be a downvote

I want this output:

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

I am using 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);

which gives me

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

How do I "add a column" like "upvotes" i.e. entries where type = 1 and the same with type = 0?

3

There are 3 answers

2
Cᴏʀʏ On BEST ANSWER

I think it might be easiest to SUM up a 1 for each row where your criteria matches:

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;

Note, you should omit type from the GROUP BY in order to get a single row back for each video.

0
Mureinik On

You could use case expression to count only the type of votes you're interested in:

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;
10
Iłya Bursov On

two variants:

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

and

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

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