0

我有一组项目。每个组都有主要的项目或标题,假设这个组里面有项目。

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

例如:这样的表

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
4

2 回答 2

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;
于 2012-06-27T13:06:05.987 回答
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
于 2012-06-27T13:03:39.027 回答