0

我有以下两张表

Table: items
ID  |  TITLE
249 | One
250 | Two
251 | Three

我对这些投票:

Table: votes
VID | IID | userid | votes
01  | 249 |    6   | 5
02  | 249 |    7   | -5
03  | 249 |    8   | 5
04  | 249 |    9   | 5
05  | 250 |    6   | -5
06  | 250 |    7   | -5
07  | 250 |    8   | 5

-5 表示投反对票,+5 表示投赞成票。假设我以用户 6 身份登录,SQL 查询会给我什么:

Table: result
ID  |  TITLE | TOTALVOTES | UPVOTES | DOWNVOTES | CURRENTUSERVOTED
249 | One    | 4          | 3       | 1         | 1
250 | Two    | 3          | 1       | 2         | 1
251 | Three  | 0          | 0       | 0         | 0
4

2 回答 2

2

CASE在聚合函数中使用表达式:

SELECT    a.ID,
          a.TITLE,
          COUNT(b.IID) AS TOTALVOTES,
          COUNT(CASE WHEN b.votes =  5 THEN 1 END) AS UPVOTES,
          COUNT(CASE WHEN b.votes = -5 THEN 1 END) AS DOWNVOTES,
          COUNT(CASE WHEN b.userid = 6 THEN 1 END) AS CURRENTUSERVOTED
FROM      items a
LEFT JOIN votes b ON a.ID = b.IID
GROUP BY  a.ID,
          a.TITLE
于 2012-09-01T20:31:06.353 回答
0

这应该工作

select I.Id, I.Title, count(*) as TotalVotes,
sum(case when votes > 0 then 1 else 0 end) as UPVOTES, 
sum(case when votes < 0 then 1 else 0 end) as DOWNVOTES,
case when sum(Case when userid = @userloged then 1 else 0 end) = 1 then 1 else 0 end as CURRENTUSERVOTED
from items I
LEFT JOIN Votes V
on I.Id = V.IID
group by I.ID, I.Title

可能是获得 CURRENTUSERVOTED 的更好方法

于 2012-09-01T20:30:53.727 回答