'Return Specific dates from Table
I have a table with report data. Each date contains 5 entries for each day as there is Group1 to Group5 in the GroupID column.
[ID] [int] IDENTITY(1,1) NOT NULL,
[Date] [date] NULL,
[GroupID] [int] NULL,
[GroupName] [varchar](50) NULL,
[GroupDescription] [varchar](500) NULL,
[GroupCount] [int] NULL
So the table looks like this and is populated every Monday:
| Date | GroupID | GroupName | GroupDescription | GroupCount |
|---|---|---|---|---|
| 2022-04-04 | 1 | Group1 | Group1 Description | 49358 |
| 2022-04-04 | 2 | GROUP2 | Group2 Description | 6158 |
| 2022-04-04 | 3 | GROUP3 | Group3 Description | 2572 |
| 2022-04-04 | 4 | GROUP4 | Group4 Description | 181 |
| 2022-04-04 | 5 | GROUP5 | Group1 Description | 15580 |
| 2022-04-12 | 1 | Group1 | Group1 Description | 49358 |
| 2022-04-12 | 2 | GROUP2 | Group2 Description | 6158 |
| 2022-04-12 | 3 | GROUP3 | Group3 Description | 2572 |
| 2022-04-12 | 4 | GROUP4 | Group4 Description | 181 |
| 2022-04-12 | 5 | GROUP5 | Group1 Description | 15580 |
I want to write a query and put it into a Stored Procedure that will produce the following
I will pass the stored procedure an int, normally 4 that will give me the last 4 Mondays (or unique date entries in case of bank holiday etc so it might update on a Tuesday)
| Date | Group1 | Group2 | Group3 | GROUP4 | Group5 |
|---|---|---|---|---|---|
| 2022-03-28 | 49358 | 6158 | 2572 | 181 | 15580 |
| 2022-04-04 | 49358 | 6158 | 2572 | 181 | 15580 |
| 2022-04-12 | 49358 | 6158 | 2572 | 181 | 15580 |
| 2022-04-19 | 49358 | 6158 | 2572 | 181 | 15580 |
I haven't tried anything as I'm not really sure where to start or if that's even possible.
Solution 1:[1]
Thanks to Eduard for the pointer. The solution was a Pivot table.
SELECT * FROM (
SELECT
[GROUPNAME],
[DATE],
[GROUPCOUNT]
FROM ReportAccountGroup
) ReportResults
PIVOT (
SUM(GroupCount)
FOR [GroupName]
IN (
[Group1],
[Group2],
[Group3],
[Group4],
[Group5]
)
) AS PivotTable
The first section get's the data. Second Section in PIVOT Sets the values for the columns. The SUM(GroupCount) is an aggregate function to supply the grouped results.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ScottUK |
