1

Is there another way I can sum up counts with less code?

I'm using a view (my only option) to try to find out if a customer spent money during any two of the last 5 calendar years

Table name: V_PERSON V_REVENUE

Columns: 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

Here's what I've tried:

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 Answers 2

1

Here's one option using exists with multiple case statements:

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

How about a CASE statement:

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 Comment

I like this one too. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.