Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom order by only printing last value

I have the script below. It only prints out one value, PLGG not all of them.

 Pot

 ABC
 MPOT
 NVPN
 PLGG   

However when I remove the order by case section then it prints all of the values. Why is that? Is it no possible to use a custom order by here?

declare @pot nvarchar(max) = ''

select @pot = @pot + QUOTENAME(pot) + ',' 
from myTbl
group by pot
order by case when pot = 'MPot' then '1'
else pot end

print(@pot)
like image 378
mHelpMe Avatar asked Oct 22 '19 13:10

mHelpMe


1 Answers

If you're trying to create a delimited list, there are "better" ways. If you're using 2017+, you can use STRING_AGG:

CREATE TABLE dbo.myTbl (Pot varchar(4));

INSERT INTO dbo.myTbl (Pot)
VALUES('ABC'),
      ('MPOT'),
      ('NVPN'),
      ('PLGG');
GO
DECLARE @Pot nvarchar(MAX)

SET @Pot = (SELECT STRING_AGG(QUOTENAME(Pot), ',') WITHIN GROUP (ORDER BY CASE WHEN Pot = 'MPot' THEN '1' ELSE Pot END) FROM dbo.myTbl);

PRINT @Pot;

If you're on 2016-, then you can use FOR XML PATH:

DECLARE @Pot nvarchar(MAX);

SET @Pot = STUFF((SELECT ',' + QUOTENAME(Pot)
                  FROM dbo.myTbl
                  ORDER BY CASE WHEN Pot = 'MPot' THEN '1' ELSE Pot END
                  FOR XML PATH(N''), TYPE).value('.', 'nvarchar(MAX)'),1,1,'');
like image 92
Larnu Avatar answered Sep 30 '22 14:09

Larnu