I bet title is not saying clearly what I am trying to achieve as complete newbie but will try to explain my problem below and hope some one will find a minute to share their wisdom :) Lets say we have a table called TYPES (Microsoft SQL Server) updated periodically ie every half hour. it consist of unique types, for each type there is number of offered transactions (if any) every update window (in reality it has millions of rows, hundreds of types and dozens of columns kept over a few years) But to keep it simple:
DateTime | Type | Offered |
---|---|---|
2021-11-04 09:00 | Type1 | 300 |
2021-11-04 09:00 | Type2 | 30 |
2021-11-04 09:00 | Type3 | 255 |
2021-11-04 09:30 | Type 1 | 244 |
2021-11-04 09:30 | Type 2 | 118 |
2021-11-04 09:30 | Type 3 | 90 |
I am trying to sum offered for a given day (24 hours period) for selected types (lets say type1 and type3) separately in one select if possible ie:
DateTime | Type1_sum | Type3_sum |
---|---|---|
2021-11-04 | 5621 | 4521 |
2021-11-05 | 5234 | 3651 |
Many thanks !
You can achieve this by grouping on the date portion of column [DateTime] then using conditional aggregation:
select
cast([DateTime] as date) as [DateTime],
sum(case [Type] when 'Type1' then [Offered] end) as Type1_sum,
sum(case [Type] when 'Type3' then [Offered] end) as Type3_sum
from YourTable
group by cast([DateTime] as date)
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.