这只是我表中的一小部分,有多个日期,但这仅是一个日期:
propertyId groupId date quantity rate
------------------------------------------------
3475 616375 2018-09-21 25 139.99
3475 626696 2018-09-21 6 144.99
3475 602361 2018-09-21 25 134.99
3475 622321 2018-09-21 5 119.99
3482 609348 2018-09-21 11 139.99
3482 621872 2018-09-21 5 75
3482 614956 2018-09-21 25 114.99
3482 583585 2018-09-21 10 139
3488 627286 2018-09-21 11 164.99
3488 619219 2018-09-21 5 129.99
3488 603781 2018-09-21 2 149.99
3488 583573 2018-09-21 2 0
我需要MAX(quantity)
以及相应的propertyId
,groupId
,date
和rate
...如果数量是平局,则是最低汇率...最后是每天SUM(quantity)
(按属性而不是分组)。
从样本中,我需要:
propertyId groupId date quantity rate sumQuantity
--------------------------------------------------------------
3475 616375 2018-09-21 25 134.99 61
3482 614956 2018-09-21 25 114.99 51
3488 627286 2018-09-21 11 164.99 20
希望这是有道理的。
答案 0 :(得分:0)
用于测试的数据Feed:
set dateformat ymd
declare @aux table (propertyId int, groupId int,[date] datetime, quantity int, rate money)
insert into @aux values (3475,616375,'2018-09-21',25,139.99)
insert into @aux values (3475,626696,'2018-09-21',6,144.99)
insert into @aux values (3475,602361,'2018-09-21',25,134.99)
insert into @aux values (3475,622321,'2018-09-21',5,119.99)
insert into @aux values (3482,609348,'2018-09-21',11,139.99)
insert into @aux values (3482,621872,'2018-09-21',5,75)
insert into @aux values (3482,614956,'2018-09-21',25,114.99)
insert into @aux values (3482,583585,'2018-09-21',10,139)
insert into @aux values (3488,627286,'2018-09-21',11,164.99)
insert into @aux values (3488,619219,'2018-09-21',5,129.99)
insert into @aux values (3488,603781,'2018-09-21',2,149.99)
insert into @aux values (3488,583573,'2018-09-21',2,0)
建议的解决方案:
select a.*
,(select sum(quantity)
from @aux
where [date] = a.[date]
and propertyId = a.propertyId
) sumQuantity
from @aux a
join (
select x.*
,(select max(rate)
from @aux
where [date] = x.[date]
and propertyId = x.propertyId
and quantity = x.qt
) rt
from (select [date]
,propertyId
,max(quantity) as qt
from @aux
group by [date], propertyId
) x
) b on a.[date] = b.[date]
and a.propertyid = b.propertyid
and qt = a.quantity
and rt = a.rate