gpt4 book ai didi

sql - 如何根据日期和类型分组

转载 作者:行者123 更新时间:2023-12-02 08:49:33 24 4
gpt4 key购买 nike

我有下表,但我无法按日期和卡片类型对它进行分组,它也应该对值求和...我遇到问题是因为我认为的 id

   OrderID | OrderDate  | CCType      |  Processed
----------- ---------------------------
451 |2012-02-27 | AMEX | 10.56
452 |2012-02-27 | VISA | 20.00
453 |2012-02-27 | MASTER CARD | 5.00
454 |2012-02-27 | OTHER | 16.00
455 |2012-02-27 | AMEX | 10.00
456 |2012-02-26 | VISA | 11.00
457 |2012-02-26 | MASTER CARD | 12.00
457 |2012-02-26 | OTHER | 5.00

它需要结束这样的事情

OrderDate  | CCType      |  Processed
-----------------------------------------
2012-02-27 | AMEX | 20.56
2012-02-27 | VISA | 20.00
2012-02-27 | MASTER CARD| 5.00
2012-02-27 | OTHER | 16.00
2012-02-26 | AMEX | 0.00
2012-02-26 | VISA | 11.00
2012-02-26 | MASTER CARD| 12.00
2012-02-26 | OTHER | 5.00

如有任何帮助,我将不胜感激。

最佳答案

棘手的部分是得到这条线

2012-02-26 AMEX        0,00

如果你不需要它,其他答案有你想要的。

declare @Order table
(
OrderID int,
OrderDate date,
CCType varchar(20),
Processed money
)

insert into @Order values
( 451, '2012-02-27', 'AMEX', 10.56),
( 452, '2012-02-27', 'VISA', 20.00),
( 453, '2012-02-27', 'MASTER CARD', 5.00),
( 454, '2012-02-27', 'OTHER', 16.00),
( 455, '2012-02-27', 'AMEX', 10.00),
( 456, '2012-02-26', 'VISA', 11.00),
( 457, '2012-02-26', 'MASTER CARD', 12.00),
( 457, '2012-02-26', 'OTHER', 5.00)

select D.OrderDate, C.CCType, sum(coalesce(T.Processed, 0)) as Processed
from (values('AMEX'),
('VISA'),
('MASTER CARD'),
('OTHER')) as C(CCType)
cross join (select distinct OrderDate
from @Order) as D(OrderDate)
left outer join @Order as T
on D.OrderDate = T.OrderDate and
C.CCType = T.CCType
group by D.OrderDate, C.CCType
order by D.OrderDate desc, C.CCType

结果:

OrderDate  CCType      Processed
---------- ----------- ---------------------
2012-02-27 AMEX 20,56
2012-02-27 MASTER CARD 5,00
2012-02-27 OTHER 16,00
2012-02-27 VISA 20,00
2012-02-26 AMEX 0,00
2012-02-26 MASTER CARD 12,00
2012-02-26 OTHER 5,00
2012-02-26 VISA 11,00

关于sql - 如何根据日期和类型分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9511902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com