在表格产品中有以下列:
a | b | cat
--------------
2 | 4 | 1
3 | 1 | 1
4 | 4 | 1
2 | 1 | 1
3 | 2 | 1
5 | 3 | 1
8 | 7 | 2
5 | 3 | 2
$sql = "SELECT
SUM(CASE
WHEN
cat = 1
AND
a > b
THEN 1 else 0 end) as prdplus
FROM product
";
在上面的查询中,我获得总和或计数的值 a 更高 然后 b
3> 1,2> 1,3> 2,5> 3
因此上述查询的输出将为: 4
prdplus
-------
4
我需要的 计数值只有+1 4 < /强>
以上查询的那些我现在需要+1值计数
3-1 = 2
2-1 = 1 // just explanation purpose , output i need in -> plus1
3-2 = 1 // just explanation purpose , output i need in -> plus1
5-3 = 2
因此,通过上述查询,我只需要+1计数 2
我没有得到如何在包括上述查询的情况下写案例,因为我需要计算在我的表格中显示如下
输出最终结果:
prdplus | plus1
----------------
4 | 2
答案 0 :(得分:1)
SELECT SUM(CASE WHEN a > b
THEN 1
else 0
end) as prdplus,
SUM(CASE WHEN a - b = 1
THEN 1
else 0
end) as prdplus1
FROM product
答案 1 :(得分:1)
检查这个。
SELECT
SUM(CASE
WHEN
a > b
THEN 1 else 0 end) as prdplus
,
SUM(CASE WHEN a - b = 1
THEN 1
else 0
end) as plus1
FROM
(
select 2 as a , 4 as b union
select 3 , 1 union
select 4 , 4 union
select 2 , 1 union
select 3 , 2 union
select 5 , 3
)
a