Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear all,

I have a little question about SQL Server 2008.
This is My Data:
NAME	DUE_IN 	VALUE
----------------------
A	15	15000
B	30	23000
A	45	15200
A	78	45000
C	45	13000
D	10	45700
D	45	45800
A	78	10220
B	10	78900
A	46	98700
A	35	45000


I want to group it into this:
NAME	DUE_IN	  VALUE
A	(<15)	  sum(value)
A	(15-30)	  sum(value)
A	(>30)	  sum(value)
B	(<15)	  sum(value)
B	(15-30)	  sum(value)
B	(>30)	  sum(value)
C	(<15)	  sum(value)
C	(15-30)	  sum(value)
C	(>30)	  sum(value)
D	(<15)	  sum(value)
D	(15-30)	  sum(value)
D	(>30)	  sum(value)


How can i do that.. I have no idea at all.. :(
Posted


one option is as follows:
>
SQL
select namee, '(<15)', sum(vvalue)  from #te where due_in <= 15 group by namee  union
select namee, '(15-30)',  sum(vvalue) from #te where due_in between 15 and 30 group by namee  union
select namee, '>30',  sum(vvalue) from #te where due_in > 30 group by namee

 
Share this answer
 
Check this:

SQL
CREATE TABLE TestData
(
  [NAME] VARCHAR(10),
  DUE_IN INT,
  [VALUE] INT
)

INSERT INTO TestData ([NAME], DUE_IN, [VALUE])
VALUES('A', 15, 15000),
('B', 30, 23000),
('A', 45, 15200),
('A', 78, 45000),
('C', 45, 13000),
('D', 10, 45700),
('D', 45, 45800),
('A', 78, 10220),
('B', 10, 78900),
('A', 46, 98700),
('A', 35, 45000)

DECLARE @tmp TABLE(RangeId INT IDENTITY(1,1), RangeName VARCHAR(10), RangeMin INT, RangeMax INT)

INSERT INTO @tmp (RangeName, RangeMin, RangeMax)
VALUES('>15', 0, 14),('15-30', 15, 30), ('>30', 31, 999999)

SELECT t1.[Name], t2.RangeName AS DUE_IN, SUM(t1.[Value]) AS [SumOfValue]
FROM TestData As t1 
    INNER JOIN @tmp AS t2 ON t1.[DUE_IN]>=t2.RangeMin AND t1.[DUE_IN]<=t2.RangeMax
GROUP BY t1.[Name], t2.RangeName, t2.RangeId
ORDER BY t1.[Name], t2.RangeId


Result:
Name 	DUE_IN 	SumOfValue
A 	15-30 	15000
A 	>30 	214120
B 	>15 	78900
B 	15-30 	23000
C 	>30 	13000
D 	>15 	45700
D 	>30 	45800



SQL Fiddle[^]
 
Share this answer
 
Comments
CHill60 7-Jan-16 10:32am    
You didn't realise this question was over 3 years old! I'm guessing it was resurrected by spam or similar
Maciej Los 8-Jan-16 1:40am    
Oh yeah. I'm gonna leave it to see what will happen next.
Thank you, Caroline.
Cheers, Maciej

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