我有一个使用uin
的SQL查询 SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert
WHERE scores_ofexpert.user_id = '30' AND scores_ofexpert.score > '0'
UNION
SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert
WHERE scores_ofexpert.user_id = '30' AND scores_ofexpert.score < '0'
UNION
SELECT Sum(scores_ofexpert.score) FROM scores_ofexpert
WHERE scores_ofexpert.user_id = '30'
这个负分数的提取和,正斜率的总和和用户的所有分数的总和; 像这样
-------------
|-10 |
-------------
|30 |
-------------
|20 |
-------------
但我希望结果为
-------------------------------------
|n_sum |p_sum |sum |
-------------------------------------
|-10 |30 |20 |
-------------------------------------
怎么做?
答案 0 :(得分:4)
您可以使用CASE
SELECT
SUM(CASE WHEN s.score < 0 THEN s.score ELSE 0 END) n_sum,
SUM(CASE WHEN s.score > 0 THEN s.score ELSE 0 END) p_sum,
SUM(s.score) `sum`
FROM scores_ofexpert s
WHERE s.user_id = '30'
答案 1 :(得分:0)
这是另一个答案
SELECT
( SELECT Sum(scores_ofexpert.score)
FROM scores_ofexpert
WHERE
scores_ofexpert.user_id = '30' AND
scores_ofexpert.score > '0'
) p_sum,
( SELECT
Sum(scores_ofexpert.score)
FROM
scores_ofexpert
WHERE
scores_ofexpert.user_id = '30' AND
scores_ofexpert.score < '0'
) n_sum,
( SELECT
Sum(scores_ofexpert.score)
FROM
scores_ofexpert
WHERE
scores_ofexpert.user_id = '30'
) sum_all
答案 2 :(得分:-1)
SELECT
sum(if(s.score > '0',s.score, 0)) as p_sum,
sum(if(s.score < '0',s.score, 0)) as n_sum,
SUM(s.score) as t_sum
FROM scores_ofexpert s
WHERE s.user_id = '30'