m.ghannaj
m.ghannaj

Reputation: 15

Group by category

I have groups of Items. Every group has main Item or header let's say this group has items inside it.

I want to select these items inside this group and make some math on them let's say I want to sum them.

For example: the table like this

Code          Description        Price
-----------   -------------      -----
12-5000       Toys
12-5000-100   FIFA Game          200$
12-5000-200   PEPSI MAN          150$
12-5000-300   X-MEN              120$
12-6000       Movies
12-6000-100   Scarface           200$
12-6000-200   BADBOYS1           200$
12-6000-300   GODFAther1         120$

The result that I am dying to get:

Description   Total
-----------   -----
Toys          470
Movies        520

Upvotes: 0

Views: 97

Answers (2)

Aaron Bertrand
Aaron Bertrand

Reputation: 280429

;WITH x AS 
(
   SELECT Code, Description FROM dbo.Table 
   WHERE price IS NULL -- =0? can't tell what blank means
)
SELECT x.Description, SUM(t.Price)
 FROM dbo.Table AS t
 INNER JOIN x 
 ON LEFT(t.Code, 7) = x.Code
 AND t.Code > x.Code
 GROUP BY x.Description;

EDIT

Since we've learned that price is literally stored as a string like '400$'...

;WITH x AS 
(
   SELECT Code, Description FROM dbo.Table 
   WHERE LEN(price) = 0
)
SELECT x.Description, SUM(CONVERT(DECIMAL(18,2), REPLACE(t.Price,'$','')))
 FROM dbo.Table AS t
 INNER JOIN x 
 ON LEFT(t.Code, 7) = x.Code
 AND t.Code > x.Code
 GROUP BY x.Description;

Upvotes: 6

Sean
Sean

Reputation: 15164

select description, sum(price)
from tableName
group by description

Can't be that easy?

EDIT

I see. You have headers (th) & rows (tr) in the same table. Then you need to isolate them into two pseudo tables. Maybe this:

select th.description, SUM(tr.price)
from tableName th
left join tableName tr
on tr.code like th.code + '-%'
where th.code like '[0-9][0-9]-[0-9][0-9][0-9][0-9]'
group by th.description

Upvotes: 0

Related Questions