我有以下数据:
ID ActionType Quantity Fee
1 Commission 1 10
1 Open 2 10
2 Commission 1 20
2 Close 3 20
3 Commission 1 30
3 Transfer 4 30
如何按ID分组并选择不是佣金的ActionType?
所以我想以
结束ID ActionType Quantity Fee
1 Open 3 20
2 Close 4 40
3 Transfer 5 60
我可以通过使用ID对分区的总和计算出数量和费用的总和,但是我无法弄清楚如何为不是佣金的货币对选择ActionType。
答案 0 :(得分:5)
试试这个:
select id,
max(case
when actiontype = 'Commision'
then null
else actiontype
end) actiontype,
sum(quantity) quantity,
sum(fee) fee
from t
group by id;
除了Commision之外,它需要最多的所有actionType以及其他总和。
答案 1 :(得分:2)
这是一种方法:
select t.id, sum(quantity) as quantity, sum(fee) as fee,
max(case when ActionType <> 'Commission' then ActionType end) as ActionType
from t
group by t.id;
这会返回一行,但没有'Commission'
。如果你有多行,那么你应该问另一个问题,并指明在这种情况下该做什么。
答案 2 :(得分:0)
(?:\d+\.)+\d*(?!tgz)
答案 3 :(得分:0)
试试这个, 根据我的理解,你试图将动作类型更改为与相同id相同的类型然后将它们分组,所以你可以做类似于下面的事情:
WITH T2 AS
(
SELECT
[ID],
[ActionType],
SUM([Quantity]) AS [Quantity],
SUM([Fee]) AS [Fee]
FROM [TSQL2012].[dbo].[StackOverFlow_300]
WHERE [ActionType] = 'Commission'
GROUP BY [ID],[ActionType]
)
SELECT
T1.[ID],
T1.[ActionType],
SUM(T1.[Quantity]) + SUM(T2.[Quantity]) AS [Quantity],
SUM(T1.[Fee]) + SUM(T2.[Fee]) AS [Fee]
FROM [TSQL2012].[dbo].[StackOverFlow_300] T1
LEFT JOIN T2 ON T2.ID = T1.ID
GROUP BY T1.[ID],T1.[ActionType]
HAVING T1.[ActionType] <> 'Commission';
答案 4 :(得分:0)
select table1.id , table1.ActionType, t.Fee , t.Quantity from
(select id , sum(fee) Fee , sum(quantity) Quantity from table1
group by id) t
inner join table1 on table1.id = t.id
where table1.actiontype <> 'Commission'
只需将查询中的table1
替换为您的表名