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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Easy SQL question for you gurus. Sum combined

Author  Topic 

o9z
Starting Member

23 Posts

Posted - 2010-09-22 : 12:23:19
I have a table that has data like this:

Material | Pounds
------------------
VEG | 2500
VEG | 1600
VEG-DM | 2000
CRN | 1200
CRN | 800
CRN-DM | 1000

My SQL statement currently looks like this:

SELECT Material, SUM(Pounds) As Pounds
From vCurrentDate
GROUP BY Material

And it returns this:

Material | Pounds
------------------
VEG | 4100
VEG-DM | 2000
CRN | 2000
CRN-DM | 1000

What I want it to return is the same thing as above...only VEG and VEG-DM are combined. And CRN and CRN-DM are combined. So it would return 2 values. VEG and CRN.

How would I do this?

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2010-09-22 : 12:53:40
Group By LEFT(Material,3)

Assuming every single material has the same form.

--
Gail Shaw
SQL Server MVP
Go to Top of Page

o9z
Starting Member

23 Posts

Posted - 2010-09-22 : 12:57:16
Is there any way to do it while retaining the "material" column in the select? I want the 2 columns it returns to be called Veg and CRN. If I leave material in there now it says that material is invalid in the select list because it is not contained in either an aggregate function of group by clause.
Go to Top of Page

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2010-09-22 : 12:59:10
DECLARE @Table TABLE (Material varchar(10),Pounds int)
INSERT INTO @Table

SELECT 'VEG',2500 UNION
SELECT 'VEG',1600 UNION
SELECT 'VEG-DM',2000 UNION
SELECT 'CRN',1200 UNION
SELECT 'CRN',800 UNION
SELECT 'CRN-DM',1000


SELECT SUM(CASE WHEN LEFT(Material ,3) = 'VEG' THEN Pounds ELSE 0 END) as Veg
, SUM(CASE WHEN LEFT(Material ,3) = 'CRN' THEN Pounds ELSE 0 END) as CRN
FROM @table


Jim

Everyday I learn something that somebody else already knew
Go to Top of Page
   

- Advertisement -