添加值计数

时间:2016-03-09 00:56:52

标签: sql oracle oracle11g

还有另一种方法可以用较少的代码来总结计数吗?

我使用视图(我唯一的选择)试图找出客户是否在过去5个日历年中的任何两年中花钱

表名:     V_PERSON     V_REVENUE

柱:     V_PERSON.ID

V.REVENUE.PersonID
V.REVENUE.Year1 revenue for the year (currently 2016)
V.REVENUE.Year2 revenue for the year (currently, 2015)
V.REVENUE.Year3
V.REVENUE.Year4
V.REVENUE.Year5

以下是我尝试的内容:

SELECT V_PERSON.ID

FROM V_PERSON

WHERE 
(

(
SELECT '1'
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID  
AND V_REVENUE.Year1 > 0
)

+

(
SELECT '1'
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID  
AND V_REVENUE.Year2 > 0
)

+

(
SELECT '1'
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID  
AND V_REVENUE.Year3 > 0
)

+

(
SELECT '1'
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID  
AND V_REVENUE.Year4 > 0
)

+

(
SELECT '1'
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID  
AND V_REVENUE.Year5 > 0
)

) >= 2

2 个答案:

答案 0 :(得分:1)

CASE陈述怎么样:

SELECT V_PERSON.ID
FROM V_PERSON
WHERE 
(
SELECT  (case when V_REVENUE.Year1 > 0 then 1 else 0 end) +  
    (case when V_REVENUE.Year2 > 0 then 1 else 0 end) +
    (case when V_REVENUE.Year3 > 0 then 1 else 0 end) +
    (case when V_REVENUE.Year4 > 0 then 1 else 0 end) +
    (case when V_REVENUE.Year5 > 0 then 1 else 0 end) 
FROM V_REVENUE
WHERE V_REVENUE.PersonID = V_PERSON.ID) >= 2

答案 1 :(得分:1)

以下是使用exists和多个case语句的一个选项:

select id
from person p 
where exists (
    select 1
    from revenue r 
    where p.id = r.personid
        and case when r.year1 > 0 then 1 else 0 end +
            case when r.year2 > 0 then 1 else 0 end +
            case when r.year3 > 0 then 1 else 0 end +
            case when r.year4 > 0 then 1 else 0 end +
            case when r.year5 > 0 then 1 else 0 end >= 2
)