按类别分组

时间:2012-06-27 13:02:22

标签: sql sql-server-2008 tsql

我有一组物品。每个组都有主要项目或标题,假设该组中有项目。

我想在这个组中选择这些项目并对它们进行一些数学计算,假设我想总结它们。

例如:像这样的表

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$

我渴望得到的结果:

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

2 个答案:

答案 0 :(得分:6)

;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;

修改

因为我们已经知道价格实际上存储为'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;

答案 1 :(得分:0)

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

不能那么容易吗?

修改

我明白了。你有标题(th)&同一个表中的行(tr)。然后你需要将它们分成两个伪表。也许这个:

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