I have a SQL Server 2005 table which lists customers and their order lines like this…
Cust | Code
Cust1 N001
Cust2 N001
Cust2 N003
Cust2 N004
Cust3 N001
Cust3 N002
Cust3 N003
Cust3 N004
I need the results to list each customer (Once) and whether they have ordered ANY items between N002 and N004. The results would therefore look like this…
Cust | Ordered?
Cust1 False
Cust2 True
Cust3 True
I have tried various combinations of All / ANY etc. The closest I got was using two queries. In the first I would add the following to get a true/false statement to the end of each line …
SELECT
Cust, Code,
CASE
WHEN Code BETWEEN 'N002' AND 'N004' THEN 'True'
ELSE 'False'
END AS Expr1
This gives the following…
Cust | Code | EXPR1
Cust1 N001 FALSE
Cust2 N001 FALSE
Cust2 N003 TRUE
Cust2 N004 TRUE
Cust3 N001 FALSE
Cust3 N002 TRUE
Cust3 N003 TRUE
Cust3 N004 TRUE
Then using a second query and grouping the results I get
Cust | Ordered?
Cust1 False
Cust2 False
Cust2 True
Cust3 False
Cust3 True
So could any one help to achieve simply…
Cust | Ordered?
Cust1 False
Cust2 True
Cust3 True
My solution is to add a variable specifying whether the value is in range, and then checking that in the case statement:
You can actually combine the two case statements into one, if you don’t care about the readability of your code.