特定行组的总和值 - SQL

时间:2017-08-04 19:52:36

标签: sql teradata

我正在尝试对所有销售/ TXN进行求和并计算整个月的不同ID,而不仅仅是单个行,其中等级为" 1"。因此,对于客户" ABC",我想要检索Jan的所有数据,以及客户" DEF"我想要他们2月份的所有数据

下面是一个示例表以及我想要的结果集(为格式化道歉)。

销售表:

Month|ID |Dte   |TXNs|Sales|Rank  
Jan  |ABC|1-5-17|1   |$15  |1  
Jan  |ABC|1-8-17|2   |$10  |2  
Feb  |ABC|2-6-17|1   |$20  |3  
Feb  |DEF|2-6-17|2   |$10  |1  
Mar  |DEF|3-5-17|1   |$40  |2  
May  |DEF|5/2/17|3   |$20  |3

期望答案:

Month|IDs|TXNs|Sales  
Jan  |1  |3   |$25  
Feb  |1  |2   |$10 

4 个答案:

答案 0 :(得分:0)

我认为您在表格中列出的ID不对吗?结果中的第一行应该是ABC而第二行是DEF吗?

无论如何,我认为这应该有效:

select month, ID, sum(TXNs), sum(SALES)
from SALES_TABLE
where
    (
        ID='ABC'
        and MONTH='Jan'
    )
    or (
        ID='DEF'
        and MONTH='Feb'
    )
group by ID, MONTH

编辑:我错过了计数部分。怎么样?

select month, count(ID), sum(TXNs), sum(SALES)
from SALES_TABLE
where rank = 1
group by month

答案 1 :(得分:0)

您可以使用group by和in子句

select month, count(ID), sum(TNXs), sum(sales)
from my_table where ( month, ID ) in (
    select distinct Month, ID
    from my_table 
    where rank = 1
)
group by month

答案 2 :(得分:0)

Count Distinct可以为您提供您正在寻找的内容:

SELECT Month, COUNT(DISTINCT ID) AS UniqueIds, COUNT(*) AS Transactions, SUM(Sales) AS TotalSales
FROM t
INNER JOIN (
    SELECT Month, ID FROM t WHERE Rank = 1
)firstRank WHERE t.ID = firstRank.ID AND t.Month = firstRank.Month
GROUP BY Month

答案 3 :(得分:0)

很难按照你的描述,但这似乎匹配:

select Month
   ,count(*) -- number of IDs
   ,sum(sumTXN) 
   ,sum(sumSales) 
from
 (
   select Month, ID, sum(TXNs) as sumTXN, sum(Sales) as sumSales
   from tab
   group by Month, ID
   having min(Rank) = 1 -- only those IDs with a Rank = 1 within this month
 ) as dt
group by Month