简体   繁体   English

特定行组的总和-SQL

[英]Sum Values From Specific Group of Rows - SQL

I am trying to sum all Sales/TXNs and count the distinct IDs for the whole month, and not just the individual row, in which the rank is "1". 我试图对所有Sales / TXN求和,并计算整个月的唯一ID,而不仅是排名为“ 1”的单个行。 So for customer "ABC", I want to retrieve all their data for Jan, and for customer "DEF" I want all their data for Feb. 因此,对于客户“ ABC”,我想要检索其1月的所有数据,对于客户“ DEF”,我想要其2月的所有数据。

Below is an example table as well as what my desired result set would be (apologies for the formatting). 下面是一个示例表,以及我想要的结果集(格式化的道歉)。

Sales Table: 销售表:

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

Desired Answer: 期望的答案:

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

I think the IDs you listed in your table aren't right? 我认为您在表格中列出的ID是不对的? Should the first row in your result be ABC and the second result be DEF? 您结果的第一行应该是ABC,第二个结果应该是DEF吗?

Anyhow, I think this should work: 无论如何,我认为这应该可行:

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

edit: I missed the count part. 编辑:我错过了计数部分。 How's this? 这个怎么样?

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

You can use group by and in clause 您可以使用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 should get you what you're looking for: 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

It's hard to follow your description, but this seems to match: 很难按照您的描述进行操作,但这似乎可以满足要求:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM