从SQL中的两个表中SELECT COUNT查询

时间:2013-10-05 01:54:18

标签: mysql sql sql-server count

我有这个查询

SELECT ( SELECT COUNT( answer ) FROM Voters WHERE answer = 'Yes' ), 
( SELECT COUNT(answer) FROM Voters WHERE answer = 'No' ), 
question, date, image
FROM Poll, Voters
WHERE Poll.poll_id = Voters.poll_id

我收到了这个重复的结果,我怎么能得到一个独特的行? 我想实现这个目标:

Yes|No|Question|date|image
 2 |1 |  ques  |date| img

enter image description here

2 个答案:

答案 0 :(得分:2)

SELECT
    SUM(CASE WHEN answer = 'yes' THEN 1 ELSE 0 END) "Yes",
    SUM(CASE WHEN answer = 'no'  THEN 1 ELSE 0 END) "NO",
    question, date, image
FROM Poll p
INNER JOIN Voters v ON p.poll_id = v.poll_id
GROUP BY question, date, image

答案 1 :(得分:1)

尝试

SELECT distinct question, date, image,( SELECT COUNT( answer ) FROM Voters WHERE answer = 'Yes' ), 
    ( SELECT COUNT(answer) FROM Voters WHERE answer = 'No' )
    FROM Poll, Voters
    WHERE Poll.poll_id = Voters.poll_id