如何计算sql的数量

时间:2017-05-03 07:52:10

标签: sql oracle

如何计算总数?

SELECT 
    COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) as "New", 
    COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Accepted"
from SHP 

结果:

NEW  Accepted
 1       5

但我需要总数 结果:6

4 个答案:

答案 0 :(得分:1)

我做这样的事情;

SELECT 
    COUNT(CASE WHEN id = 1 THEN 1 END) as New, 
    COUNT(CASE WHEN id = 2 THEN 5 END) as Accepted,
    COUNT(CASE WHEN id = 1 THEN 1 
               WHEN id = 2 THEN 5 END) as Total
FROM SHP 

这正是CASE语句应该用于的,逻辑非常简单。这样可以避免在同一个字段上执行多次计算。

请注意,THEN语句中的值根本没有在此实例中使用,它只是在执行COUNT数字而不是执行{ {1}}。我还删除了SUM,因为无论如何这都是ELSE NULL默认执行的操作。

如果你的意图是CASE,那么就这样做;

SUM

示例

假设您的数据库中只有两个值,1和2,我们可以创建这样的测试数据;

SELECT 
    SUM(CASE WHEN id = 1 THEN 1 END) as New, 
    SUM(CASE WHEN id = 2 THEN 5 END) as Accepted,
    SUM(CASE WHEN id = 1 THEN 1 
             WHEN id = 2 THEN 5 END) as Total
FROM SHP 

并使用此查询;

CREATE TABLE #SHP (id int)
INSERT INTO #SHP (id)
VALUES (1),(2)

给出这个结果;

SELECT 
    SUM(CASE WHEN id = 1 then 1 END) as New, 
    SUM(CASE WHEN id = 2 then 5 END) as Accepted,
    SUM(CASE WHEN id = 1 THEN 1 
             WHEN id = 2 THEN 5 END) as Total
FROM #SHP 

答案 1 :(得分:0)

试试这个:

SELECT 
    COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) + 
    COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Total"
from SHP 

答案 2 :(得分:0)

您可以将查询包装到子查询中并执行以下操作:

SELECT SUM(New) as New, Sum(Accepted) as Accepted, Sum(New + Accepted) as Total FROM
(SELECT 
    COUNT(CASE WHEN SHP.id = 1 then 1 ELSE NULL END) as "New", 
    COUNT(CASE WHEN SHP.id = 2 then 5 ELSE NULL END) as "Accepted"
from SHP) as SubQuery

如果您不想重复计算并将两者加在一起,那就是这样。

答案 3 :(得分:0)

试试这个

with s1 as(
SELECT 
    COUNT(CASE WHEN SHP.id = 1 then 1 ELSE 0 END) as "New" 
from SHP 
),s2 as
(
SELECT  
    COUNT(CASE WHEN SHP.id = 2 then 5 ELSE 0 END) as "Accepted"
from SHP 
)
select sum("New"+  "Accepted") from s1,s2