I have the following data in a table. There will be many LocationID
and for each location, there will be 120 months (fixed 10 years) of data.
| LOC | Yr | Mon | Amt |
| ------------ | ------------ | ------------ | ------------ |
| 101 | 2023 | 4 | 65.45 |
| 101 | 2023 | 5 | 65.45 |
| 101 | 2023 | 6 | 65.45 |
| 101 | 2023 | 7 | 65.45 |
| 101 | 2023 | 8 | 65.45 |
| 101 | 2023 | 9 | 65.45 |
| 101 | 2023 | 10 | 65.45 |
| 101 | 2023 | 11 | 65.45 |
| 101 | 2023 | 12 | 65.45 |
| 101 | 2024 | 1 | 65.45 |
| 101 | 2024 | 2 | 65.45 |
| 101 | 2024 | 3 | 65.45 |
| 101 | 2024 | 4 | 34.12 |
| 101 | 2024 | 5 | 34.12 |
| 101 | 2024 | 6 | 34.12 |
I'm trying to get it in a format like the following (ascending year-month order):
LOC | 2023-Apr | 2023-May | 2023-Jun | 2023-Jul | 2023-Aug | 2023-Sep | 2023-Oct | 2023-Nov | 2023-Dec | 2024-Jan | ..... |
---|---|---|---|---|---|---|---|---|---|---|---|
101 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 | 65.45 |
I got started with the following query to combine the date and month
SELECT
loc, CAST(yr AS varchar) + '-' + DATENAME(mm, DATEADD(mm, Mon, -1)) [Period],
Amt
FROM
TBL
WHERE
loc = 101 AND plID = 11
ORDER BY
Yr, Mon
Which returns this result:
loc | Period | Amt |
---|---|---|
101 | 2023-April | 65.45 |
101 | 2023-August | 65.45 |
101 | 2023-December | 65.45 |
101 | 2023-July | 65.45 |
Needing some help figure out the best approach to get the data from this to the desired format/layout that I mentioned in the second table above..
Suggestions?
1条答案
按热度按时间l7wslrjt1#
I came up with the following query which works. I had to put the data in a temp table as the CTE was not available in the second select (@query)! Also, the columns are not sorted in the way I want.
Suggestions?