Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all I have a table which contains the name of person and item he has(1-50 range values). means two columns only.Now I have to select as :

<big>Name qty(1-10) qty(10-20) qty(20-30) qty(30-40) qty(40-50)
A 2
B 38
C 13
D 7</big>
Note: Here value is the exact quantity a person have.


I want to ask how to perform this in a single query. I know I can have multiple if else for the same column like if value is between 1- 10 then select it under first column else leave it blank.
Second is using multiple if else is okay or it is the worse practice.
Posted

SQL
SELECT 
Name,
SUM(CASE WHEN qty > 1  AND qty <= 10 THEN qty ELSE 0 END) as qty1_10,
SUM(CASE WHEN qty > 10 AND qty <= 20 THEN qty ELSE 0 END) as qty11_20,
SUM(CASE WHEN qty > 20 AND qty <= 30 THEN qty ELSE 0 END) as qty21_30,
SUM(CASE WHEN qty > 30 AND qty <= 40 THEN qty ELSE 0 END) as qty31_40,
SUM(CASE WHEN qty > 40 AND qty <= 50 THEN qty ELSE 0 END) as qty41_50
FROM Table1
GROUP BY Name
 
Share this answer
 
Comments
shekhb 14-Nov-12 23:13pm    
Thanks Sir,
Thanks very much for the solution and I am happy to accept this as a solution but can you please comment on the performance of this query is there any other way of doing same which is more optimized. May these comments are due to lack of knowledge so need your guidance.

Thanks
chaau 14-Nov-12 23:25pm    
I think if you have an index on Name, the query will work very fast
Use Case

SQL
Syntax

CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] [...]]
[ELSE expressionN]
END
Example:

DECLARE @TestVal INT --Declare a variable
SET @TestVal = 3 --Assiggning Variable value as 3

SELECT
CASE @TestVal
WHEN 1 THEN 'First' --@TestValvalue is 1 then 'First' return
WHEN 2 THEN 'Second'--@TestValvalue is 2 then 'Second' return
WHEN 3 THEN 'Third'--@TestValvalue is 3 then 'Third' return
ELSE 'Other'--@else then 'Other' return
END


More details Refer
http://blog.sqlauthority.com/2007/04/14/sql-server-case-statementexpression-examples-and-explanation/[^]

http://msdn.microsoft.com/en-us/library/ms181765.aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900