在SQL中粗化GROUP BY

时间:2012-03-22 08:38:31

标签: sql

给出以下表格的表格

CustumerID | Amount
-------------------
1          | 100 
1          | 50
2          | 30
3          | 40
4          | 50

SQL查询

SELECT  SUM(Amount)
GROUP BY Customer ID

将返回

CustomerID | Amount
-------------------
1          | 150
2          | 30
3          | 40
4          | 50

是否有办法'粗化'GROUP BY语句,以便将CustomerIDs 1和2以及CustomerID 3和4组合在一起,即结果如

CustomerID   | Amount
---------------------
1,2          | 180
3,4          | 90

被退回?

3 个答案:

答案 0 :(得分:2)

当然,取决于你想如何分组它们。

在MySQL中:

select group_concat(customerid) as customers, sum(amount) as amount
from your_table
group by floor((customerid+1)/2) --or another function that returns a unique value for the customers in the group

在Oracle 11g中:

select list_agg(customerid, ',') as customers, sum(amount) as amount
from your_table
group by trunc((customerid+1)/2) --or another function that returns a unique value for the customers in the group

答案 1 :(得分:2)

select case when CustomerID=1 or CustomerID=2 then '1,2'
            when CustomerID=3 or CustomerID=4 then '3,4'
                                              else CustomerID
       end
     , sum(amout)
from TABLE
group by case when CustomerID=1 or CustomerID=2 then '1,2'
              when CustomerID=3 or CustomerID=4 then '3,4'
                                                else CustomerID
         end

答案 2 :(得分:0)

如果你不想创建一个表,我想你至少应该创建一个VIEW,如果你想要由你的客户组成一个任意组

这是一个SQL SERVER 2005及更高版本的解决方案,基于一个非常有趣的答案 https://stackoverflow.com/a/273330/1236044

create table TABLETEST ([CustomerID] INT, [AMOUNT] INT)
go
insert into TABLETEST values (1,100)
insert into TABLETEST values (1,50)
insert into TABLETEST values (2,30)
insert into TABLETEST values (3,40)
insert into TABLETEST values (4,50)
go

create view VIEWTESTCAT as
    select TABLETEST.*,'category1' as [Category] from TABLETEST where CustomerID in (1,2)
    union
    select TABLETEST.*,'category2' as [Category] from TABLETEST where CustomerID in (3,4)
go

Select [NameValues], SUM([Amount]) from
(
  SELECT  
    STUFF((SELECT distinct ',' + convert(nvarchar(max),VIEWTESTCAT.[CustomerID])  FROM VIEWTESTCAT
      where VIEWTESTCAT.Category = VIEWTESTCATALIAS.Category
      order by ',' + convert(nvarchar(max),VIEWTESTCAT.[CustomerID])
      FOR XML PATH ('')
     ),1,1,'') AS NameValues
    , Amount
  FROM VIEWTESTCAT VIEWTESTCATALIAS
) as TABLETESTAUX
group by NameValues

drop view VIEWTESTCAT
go

drop table TABLETEST
go