每个X的值的总和按Y分组

时间:2017-03-30 09:16:19

标签: sql sql-server tableau

declare @table table (Customer  char(1), Transaction char(3), Discount float);
insert into @table values 
('A', '001', '10.1'),
('A', '001', '10.1'),
('A', '002', '20.2'),
('B', '003', '30.3'),
('B', '004', '40.4')

我正在尝试做这样的事情:

SELECT Customer, (SELECT SUM(Discount) WHERE Transaction IS DISTINCT)
FROM @table
GROUP BY Customer

结果应如下:

Customer    Total Discount
--------------------------
A                   30.3       
B                   70.7

所以基本上我需要为每个交易的每个客户提供所有折扣,因为它们有时会在我的数据中重复出现。

4 个答案:

答案 0 :(得分:3)

您可以使用子查询仅获取所有不同的行;

SELECT Customer, SUM(Discount) as Total_Discount FROM 
(
 SELECT DISTINCT Customer, Transaction, Discount FROM @table
) x
group by Customer

回答你的问题;如果存在相同客户,同一交易但折扣不同的情况,您必须决定是将其视为不同的交易,还是仅获得最高折扣或最低折扣。

获得最高折扣,

SELECT Customer, SUM(Discount) as Total_Discount FROM 
(
 SELECT Customer, Transaction, MAX(Discount) as Discount FROM @table
 GROUP BY Customer, Transaction
) x
group by Customer

获得最低折扣

SELECT Customer, SUM(Discount) as Total_Discount FROM 
(
 SELECT Customer, Transaction, MIN(Discount) as Discount FROM @table
 GROUP BY Customer, Transaction
) x
group by Customer

如果您打算将其视为完全不同的交易(意味着它也会被添加到总数中);无需进一步更改代码。

答案 1 :(得分:2)

首先根据3列从临时表中获取DISTINCT值。然后根据GROUP BY客户的SUM折扣值

  SELECT A.Customer, SUM(A.Discount) as Total_Discount 
  FROM 
   (
     SELECT DISTINCT Customer, Transaction, Discount FROM @table
   ) A
  GROUP BY A.Customer

答案 2 :(得分:0)

使用行号

SELECT Customer
    ,sum(Discount) as Total_Discount 
FROM (
    SELECT Customer
        ,[Transaction]
        ,Discount
        ,row_number() OVER (
            PARTITION BY Customer
            ,[Transaction] ORDER BY Discount
            ) AS rn
    FROM @table
    ) t
WHERE rn = 1
GROUP BY Customer

答案 3 :(得分:0)

通过内联查询从表中获取不同的记录并命名为"内联"然后从"内联"中选择客户和总和折扣。像

SELECT Inline.Customer,
SUM(Inline.[Discount]) FROM
(SELECT DISTINCT Customer,[Discount] FROM @table)   Inline
  GROUP BY Inline.Customer