![](/img/trans.png)
[英]Update group of rows to delete a specific total amount from the sum of the rows SQL
[英]Sum Values From Specific Group of Rows - SQL
我试图对所有Sales / TXN求和,并计算整个月的唯一ID,而不仅是排名为“ 1”的单个行。 因此,对于客户“ ABC”,我想要检索其1月的所有数据,对于客户“ 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
我认为您在表格中列出的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.