来自此查询:
SELECT
v.idutente AS idutente,
vl.idvideo AS idvideo,
(vl.likeY-vl.unlikeY) AS sott
FROM video_likeunlike AS vl
LEFT OUTER JOIN video AS v
ON vl.idvideo = v.ID
WHERE status = '1'
我有来自表
的数据idutente idvideo likeY unlikeY sott
------------------------------------------------
1 70 2 5 -3
2 81 6 10 -4
1 52 200 198 2
1 54 30 2 28
2 67 20 5 15
3 22 12 0 12
我需要这个结果,可能吗?
idutente likeY unlikeY sott
------------------------------------------------
1 232 205 27
2 26 15 11
3 12 0 12
我尝试使用此查询
SELECT
v.idutente AS idutente,
vl.idvideo AS idvideo,
vl.likeY as likeY,
vl.unlikeY as unlikeY,
(vl.likeY-vl.unlikeY) AS sott
FROM video_likeunlike AS vl
LEFT OUTER JOIN video AS v
ON vl.idvideo = v.ID
WHERE status = '1'
GROUP BY v.idutente
ORDER BY sott DESC
答案 0 :(得分:3)
请对选择列使用聚合SUM()操作。查询可以修改为:
SELECT v.idutente AS idutente,
vl.idvideo AS idvideo,
SUM(vl.likeY) AS likeY,
SUM(vl.unlikeY) AS unlikeY,
SUM(vl.likeY-vl.unlikeY) AS sott
FROM video_likeunlike AS vl
LEFT OUTER JOIN video AS v ON vl.idvideo = v.ID
WHERE status = '1'
GROUP BY v.idutente
ORDER BY sott DESC
答案 1 :(得分:1)
看起来你想使用sql sum()函数
SELECT
v.idutente AS idutente,
sum(vl.likeY) as likeY,
sum(vl.unlikeY) as unlikeY,
sum(vl.likeY)-sum(vl.unlikeY) AS sott
FROM video_likeunlike AS vl
LEFT OUTER JOIN video AS v
ON vl.idvideo = v.ID
WHERE status = '1'
GROUP BY v.idutente
ORDER BY sott DESC
答案 2 :(得分:1)
SELECT idutente,
SUM(likeY) likeY,
SUM(unlikeY) unlikeY,
SUM(sott) sott
FROM mytable
GROUP BY idutente
ORDER BY sott DESC
在SQL Fiddle中试用。
答案 3 :(得分:0)
将您的第一个查询用作子查询,然后执行分组。
<强>查询强>
SELECT t.idutente, SUM(t.likeY) as likeY, SUM(t.unlikeY) as unlikeY from(
SELECT
v.idutente AS idutente,
vl.idvideo AS idvideo,
vl.likeY,
vl.unlikeY,
(vl.likeY-vl.unlikeY) AS sott
FROM video_likeunlike AS vl
LEFT OUTER JOIN video AS v
ON vl.idvideo = v.ID
WHERE status = '1'
) t
GROUP BY t.idutente
ORDER t.sott desc;