我有一张桌子:
function highlightSquare() {
'use strict';
$('.square').on('mouseenter', function () {
$(this).css('background', genColor());
});
我希望得到一个这样的结果:
------------------------------------------
Uid | mount | category
-----------------------------------------
1 | 10 | a
1 | 3 | b
3 | 7 | a
4 | 1 | b
4 | 12 | a
4 | 5 | b
1 | 2 | c
2 | 5 | d
由uid分组;
Suma是sum(mount),其中catagory ='a';
Sumnota是sum(mount),其中catagory<> '一个';
任何想法怎么做?
答案 0 :(得分:1)
在CASE
函数中使用SUM()
语句进行条件聚合:
SELECT
uid
, SUM(CASE WHEN category = 'a' THEN mount ELSE 0 END) AS suma
, SUM(CASE WHEN category IS DISTINCT FROM 'a' THEN mount ELSE 0 END) AS sumnota
FROM
yourtable
GROUP BY uid
ORDER BY uid
我正在使用IS DISTINCT FROM
子句来正确处理类别列中的NULL
值。如果不是您的情况,您只需使用<>
运算符。
来自documentation(大胆强调我的):
普通比较运算符产生null(表示“未知”),而不是 当任一输入为空时,为true或false。
对于非空输入,IS DISTINCT FROM与&lt;&gt;相同运营商。但是,如果两个输入都为null,则返回false;如果只有一个输入为null,则返回,返回true 。
答案 1 :(得分:0)
这里的解决方案更多&#34; verbosed&#34;比接受的答案。
WITH
t_suma AS ( SELECT uid, SUM(mount) AS suma
FROM your_table
WHERE category = 'a'
GROUP BY uid ),
t_sumnota AS ( SELECT uid, SUM(mount) AS sumnota
FROM your_table
WHERE category <> 'a' or category is NULL
GROUP BY uid )
SELECT distinct y.uid, COALESCE( suma, 0) AS suma, COALESCE( sumnota, 0 ) AS sumnota
FROM your_table y LEFT OUTER JOIN t_suma ON ( y.uid = t_suma.uid )
LEFT OUTER JOIN t_sumnota ON ( y.uid = t_sumnota.uid )
ORDER BY uid;