2013-07-25 124 views
15

以下是列表数据。按两列分组,每行显示累计总数

Code ItemCount Type  Amount 
---------------------------------------- 
B001 1   Dell   10.00 
B001 1   Dell   10.00 
B001 1   Apple  10.00 
B001 2   Apple  20.00 
B001 2   Apple  20.00 
B114 1   Apple  30.50 
B114 1   Apple  10.00 

我需要一个结果组通过代码和类型,总的ItemCount并获得总计的Amount的每一排。

这可能吗?

Code ItemCount Type  Amount 
---------------------------------------- 
B001 2   Dell   20.00 
B001 5   Apple   50.00 
B114 2   Apple   40.50 
+0

为什么一切都具有相同的总额是多少? – hallie

回答

22

请尝试:

SELECT 
    Code, 
    SUM(ItemCount) ItemCount, 
    Type, 
    SUM(Amount) Amount 
FROM 
    YourTable 
GROUP BY Code, Type 
ORDER BY Code 
+0

你正在按itemcount分组,你确定它会给出正确的结果吗? – Abubakkar

+0

是的,你是对的@阿布。那是一个错误。 – TechDo

+0

使用该命令,它的工作原理 – user2617053

1

你可以试试这个查询:

SELECT Code,SUM(ItemCount) AS ItemCount,Type,SUM(Amount) AS Amount 
FROM 
    table 
GROUP BY Code, Type 

这会给你正确的结果。你需要分组CodeType而不是ItemCount

3

这看起来像家庭作业。

(我发誓,我认为这是标记为MySQL时,我第一次看这个问题,但标题可以清楚地显示了MS SQL)

对于MySQL, 此查询将返回指定的结果集:

SELECT t.Code 
    , SUM(t.ItemCount) AS ItemCount 
    , t.Type 
    , s.Amount AS Amount 
    FROM mytable t 
CROSS 
    JOIN (SELECT SUM(r.Amount) AS Amount 
      FROM mytable r 
     ) s 
GROUP 
    BY t.Code 
    , t.Type 
ORDER BY t.Code ASC, t.Type DESC 

对于其他数据库,删除对于MySQL列周围的反引号。

如果需要保留大小写,对于Oracle,标识符用双引号括起来。对于SQL Server,标识符用方括号括起来。对于MySQL,标识符被反引号括起来。

0

的金额你给从样本数据不同,但这个工程的样本数据值:

SELECT Code, SUM(ItemCount) AS ItemCount, [Type], SUM(Amount) AS Amount 
FROM dbo.TestSubs GROUP BY Code,[Type] ORDER BY Code 
0

如果我的理解是正确的,各行的实际总数超过ITEMCOUNT和数量的乘积那么你可以使用下面的代码。如果不使用@ Abu的代码。

;WITH cte AS 
(
    SELECT Code, ItemCount, Type, Amount, ItemCount * Amount AS TotalAmount FROM <Table> 
) 
SELECT 
    Code, 
    SUM(ItemCount), 
    Type, 
    SUM(TotalAmount) 
FROM cte 
GROUP BY Code, Type 
2

你可以试试这个简单的解决方案:

select Code,sum(ItemCount),Type,sum(Amount) from table group by code,type 

了解“按组”会来得心应手