简体   繁体   中英

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". So for customer "ABC", I want to retrieve all their data for Jan, and for customer "DEF" I want all their data for Feb.

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? Should the first row in your result be ABC and the second result be 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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