对特定行组的值求和 - SQL

Sum Values From Specific Group of Rows - SQL

我正在尝试对所有 Sales/TXNs 求和并计算整个月的不同 ID,而不仅仅是排名为“1”的单个行。因此,对于客户 "ABC",我想检索他们 1 月份的所有数据,对于客户 "DEF",我想要他们 2 月份的所有数据

下面是一个示例 table 以及我想要的结果集(对格式表示歉意)。

销售额Table:

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

想要的答案:

Month|IDs|TXNs|Sales  
Jan  |1  |3   |  
Feb  |1  |2   | 

我认为您在 table 中列出的 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

您可以使用 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

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

很难理解你的描述,但这似乎符合:

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