I am looking for a way to concatenate the rows into a comma separated string.
Example:
I am looking for result as below where Result Seq column should concatenate the result column row by row values in order of Inspectiondate
within group of ProductNumber
, Purchaseordernumber
.
DECLARE @Table TABLE(PRODUCTNUMBER VARCHAR(10),PURCHASEORDERNUMBER
VARCHAR(11), INSPECTIONDATE date,BOOKINGTYPEDesc varchar(20),RESULT
VARCHAR(10));
INSERT INTO @table(PRODUCTNUMBER,PURCHASEORDERNUMBER,INSPECTIONDATE,BOOKINGTYPEDesc,RESULT)
VALUES
('117858-EUC', '400P0003270', '2023-04-27','FirstInspection','Pass'),
('117858-EUC', '400P0003270', '2023-04-29','FirstInspection', 'Fail'),
('117858-EUC', '400P0003270', '2023-05-02','SecondInspection', 'Reject'),
('117858-EUC', '400P0003270', '2023-05-15','FirstInspection', 'Abort'),
('117858-EUC', '400P0003270', '2023-05-20','FirstInspection', 'Pass'),
('117858-EUC', '400P0003270', '2023-05-21','SecondInspection', 'Fail'),
('117858-EUC', '400P0003327', '2023-04-27','FirstInspection', 'Pass'),
('117858-EUC', '400P0003327', '2023-04-28','FirstInspection', 'Pass'),
('117858-EUC', '400P0003327', '2023-04-29','FirstInspection', 'Pass'),
('117858-EUC', '400P0003327', '2023-05-01','FirstInspection', 'Fail'),
('117858-EUC', '400P0003327', '2023-05-03','Second', 'Fail'),
('117858-EUC', '400P0003327', '2023-05-09','FirstInspection', 'Reject'),
('117858-EUC', '400P0003327', '2023-05-12','Second', 'Pass'),
('117858-EUC', '400P0003327', '2023-05-15','FirstInspection', 'Pass')
Any help on the SQL query.
3条答案
按热度按时间r6hnlfcb1#
If you want to generate a
ResultSeq
column which concatenates the values in theResult
column, row by row, ordered byInspectiondate
, partitioned byProductNumber
andPurchaseordernumber
, then the following approach is an option:yhived7q2#
Thanks for all your inputs. with the help of the links you have given,
I have managed to get the output which i am looking for. SQL Query:
Output:
vzgqcmou3#
Another option is a recursive CTE.
Begin by selecting the first row for each group. We can do this using
ROW_NUMBER
.For each row in the recursive section, get the next "first row" starting from after our current one.
We must use
ROW_NUMBER
again becauseTOP
is not allowed in a rCTE.The compiler can optimize away the row-numbering into a
TOP
.db<>fiddle