Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Vinnie881
Master Smack Fu Yak Hacker
1231 Posts |
Posted - 2006-12-09 : 00:01:32
|
| I am able to do this using UNION clauses, but is there a better wayCreate Table Test(amount)Insert into test(Amount)select 10 unionselect 20 unionselect 30 unionselect 40 unionselect 50 unionselect 60 unionselect 70 unionselect 80 unionWhat I want to output is thisDesc|Count|Sum'less than or equal to 30', 3 , 60'31 to 50', 2, 90'51 to 70', 2, 130'over 70',1,80I can currently achieve this by a union query like belowSelect 'less than or equal to 30',count(*),sum(amount)from testwhere amount <= 30Union allSelect '31 to 50',count(*),sum(amount)from testwhere amount between 30 and 50Union alletc.Is there a better way to do this? |
|
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2006-12-09 : 02:37:55
|
| Read about Cross-tab Reports in sql server help fileMadhivananFailing to plan is Planning to fail |
 |
|
|
Jeff Moden
Aged Yak Warrior
652 Posts |
Posted - 2006-12-10 : 17:31:12
|
Uh huh... except this isn't a cross-tab problem...Vinnie, This should do the trick... notice the extra "<" in the <= 30 description to take advantage of the natural sort order...Create Table #Test(amount INT)Insert into #Test(Amount)select 10 unionselect 20 unionselect 30 unionselect 40 unionselect 50 unionselect 60 unionselect 70 unionselect 80 SELECT [Desc] = CASE WHEN Amount <= 30 THEN '<Less than or equal to 30' WHEN Amount BETWEEN 31 AND 50 THEN '31 to 50' WHEN Amount BETWEEN 51 AND 70 THEN '51 to 70' WHEN Amount > 70 THEN 'Over 70' END, [Count] = COUNT(Amount), [Sum] = SUM(Amount) FROM #Test GROUP BY CASE WHEN Amount <= 30 THEN '<Less than or equal to 30' WHEN Amount BETWEEN 31 AND 50 THEN '31 to 50' WHEN Amount BETWEEN 51 AND 70 THEN '51 to 70' WHEN Amount > 70 THEN 'Over 70' END ORDER BY [Desc] --Jeff Moden |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-12-10 : 17:40:10
|
If you somehome, in the future, can't rely on the natural order, this can be one approach.-- prepare test datadeclare @test table (amount int)Insert @testselect 10 union allselect 20 union allselect 30 union allselect 40 union allselect 50 union allselect 60 union allselect 70 union allselect 80-- do the workSELECT SUBSTRING(q.[Desc], 3, 8000) AS [Desc], COUNT(*) [Count of Amount], SUM(Amount) [Sum of Amount]FROM ( SELECT CASE WHEN Amount <= 30 THEN '1#Less than or equal to 30' WHEN Amount BETWEEN 31 AND 50 THEN '2#31 to 50' WHEN Amount BETWEEN 51 AND 70 THEN '3#51 to 70' WHEN Amount > 70 THEN '4#Over 70' END AS [Desc], Amount FROM @Test ) qGROUP BY SUBSTRING(q.[Desc], 3, 8000)ORDER BY MIN(LEFT(q.[Desc], 1)) Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|
|
|
|