May 9, 2023 at 1:27 pm
Hi Team,
I have data like below and expected output is like this.
--Expected o/p
--Jan-2022,Jan-2023,January-2022,01-01-2023,Jan-2023,Jan-2023
Can you please help me on this.
USE [Tempdb]
GO
/****** Object: Table [dbo].[tempIssueRange] Script Date: 09-05-2023 18:53:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tempIssueRange](
[IssueID] [int] NULL,
[IssueName] [varchar](110) NULL,
[IssueDate] [date] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1024, N'Jan-2022', CAST(N'2022-01-01' AS Date))
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1176, N'January-2022', CAST(N'2022-01-01' AS Date))
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1188, N'Jan-2023', CAST(N'2023-01-01' AS Date))
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1260, N'01-01-2023', CAST(N'2023-01-01' AS Date))
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1312, N'Jan-2023', CAST(N'2023-01-01' AS Date))
GO
INSERT [dbo].[tempIssueRange] ([IssueID], [IssueName], [IssueDate]) VALUES (1324, N'Jan-2023', CAST(N'2023-01-01' AS Date))
GO
select * from tempIssueRange
--Expected o/p
--Jan-2022,Jan-2023,January-2022,01-01-2023,Jan-2023,Jan-2023
May 9, 2023 at 1:36 pm
You just want to concatenate all the IssueName values? If you don't care about order, you can use STRING_AGG function:
SELECT STRING_AGG(IssueName,',') AS IssueNames FROM dbo.tempIssueRange;
May 9, 2023 at 1:57 pm
Hi Ratbak,
Thanks for your reply but order is the only my main problem.
--Expected o/p : Previours years following by current year data
--Jan-2022,January-2022,Jan-2023,01-01-2023,Jan-2023,Jan-2023
Thanks
Bhanu
May 9, 2023 at 5:45 pm
Hi Ratbak,
Thanks for your reply but order is the only my main problem.
--Expected o/p : Previours years following by current year data --Jan-2022,January-2022,Jan-2023,01-01-2023,Jan-2023,Jan-2023
Thanks
Bhanu
Since this seems new to you, read the documentation...
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
... which should lead you to doing the following...
SELECT STRING_AGG(IssueName, ',') WITHIN GROUP (ORDER BY IssueID)
FROM dbo.tempIssueRange
;
Results:
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply