How to use distinct insteade of using group by ?

ahmed salah 3,216 Reputation points
2021-01-05T03:00:15.567+00:00

I work on SQL server 2012 I need to replace group by with distinct

so How to modify next statement to use distinct instead of group by

sample data

create table #allfeatures
(
FeatureName  nvarchar(100),
DisplayOrder Int
)


insert into #allfeatures(FeatureName,DisplayOrder)
values
('Competitor Supply Current',7),
('Competitor Minimum Supply Voltage',   5),
('Competitor Maximum Supply Voltage',   4),
('Competitor Minimum Operating Temperature',    8),
('Competitor Maximum Operating Temperature',    9),
('Competitor Operating Frequency',  6),
('Competitor Applications', 3),
('NXP Supply Current',  7),
('NXP Minimum Supply Voltage',  5),
('NXP Maximum Supply Voltage',  4),
('NXP Minimum Operating Temperature',   8),
('NXP Maximum Operating Temperature',   9),
('NXP Operating Frequency', 6),
('NXP Applications',    3),
('Competitor Automotive',   1),
('NXP Automotive',  1),
('Competitor SecurityApproval', 1),
('NXP SecurityApproval',    1),
('Competitor Normalized Package Name',  2),
('NXP Normalized Package Name', 2),
('Competitor ZTemperatureGrade',    10),
('NXP ZTemperatureGrade',   10)

DECLARE @result NVARCHAR(MAX)
SELECT  @result = ( SELECT  STUFF(( SELECT   ',[' +  FeatureName + ']'  FROM #allfeatures
group by FeatureName,displayorder
ORDER BY  (CASE WHEN displayorder IS NULL THEN 1 ELSE 0 END) asc,displayorder,FeatureName asc                                
FOR
XML PATH('')
), 1, 1, '') AS [Output]  )
select @result
Developer technologies Transact-SQL
SQL Server Other
{count} votes

5 answers

Sort by: Most helpful
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-01-05T07:17:28.767+00:00

    53554-image.png

    Please try to add all the columns selected in select to the order by list.

    I found a similar problem, including the replacement of distinct and group by, and the error you mentioned:
    ORDER BY items must appear in the select list if SELECT DISTINCT is specified

    Echo

    0 comments No comments

  2. ahmed salah 3,216 Reputation points
    2021-01-05T09:44:37.933+00:00

    i try as below
    DECLARE @result NVARCHAR(MAX)
    SELECT @result = ( SELECT STUFF(( SELECT distinct ',[' + FeatureName + ']' FROM #allfeatures
    ORDER BY (CASE WHEN displayorder IS NULL THEN 1 ELSE 0 END) asc,displayorder,FeatureName asc
    FOR
    XML PATH('')
    ), 1, 1, '') AS [Output] )
    select @result

    really i don't need display order on select so what i do to solve issue

    i get error
    ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

    0 comments No comments

  3. Viorel 122.6K Reputation points
    2021-01-05T12:13:20.99+00:00

    Your original query returns a comma-separated list of features, which does not include duplicates for provided data. Give the expected string if the result is not good.

    Do you want to exclude possible duplicates, ignoring the unneeded DisplayOrder? Then consider the next query:

    set @result = STUFF(( SELECT  ',[' +  FeatureName + ']'     
        FROM ( select distinct FeatureName from #allfeatures ) d
        ORDER BY FeatureName asc                                 
        FOR
        XML PATH('')
        ), 1, 1, '')
    
    0 comments No comments

  4. EchoLiu-MSFT 14,621 Reputation points
    2021-01-06T03:26:19+00:00

    Try:

        DECLARE @result NVARCHAR(MAX)
        SELECT @result = ( SELECT STUFF(( SELECT distinct ',[' + FeatureName + ']' f
        FROM #allfeatures
        ORDER BY f
        FOR
        XML PATH('')
        ), 1, 1, '') AS [Output] )
        select @result
    

    Please provide the desired output.

    Regards
    Echo

    0 comments No comments

  5. Yitzhak Khabinsky 26,586 Reputation points
    2021-01-08T15:08:29.773+00:00

    Here a solution without both DISTINCT and GROUP BY clauses.

    It is based on XML and XQuery, and using the distinct-values() XQuery function to achieve the desired outcome.

    SQL

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, FeatureName  nvarchar(100), DisplayOrder Int);
    INSERT INTO @tbl(FeatureName,DisplayOrder) VALUES
    ('Competitor Supply Current',7),
    ('Competitor Minimum Supply Voltage',    5),
    ('Competitor Maximum Supply Voltage',    4),
    ('Competitor Minimum Operating Temperature',    8),
    ('Competitor Maximum Operating Temperature',    9),
    ('Competitor Operating Frequency',    6),
    ('Competitor Applications',    3),
    ('NXP Supply Current',    7),
    ('NXP Minimum Supply Voltage',    5),
    ('NXP Maximum Supply Voltage',    4),
    ('NXP Minimum Operating Temperature',    8),
    ('NXP Maximum Operating Temperature',    9),
    ('NXP Operating Frequency',    6),
    ('NXP Applications',    3),
    ('Competitor Automotive',    1),
    ('NXP Automotive',    1),
    ('Competitor SecurityApproval',    1),
    ('NXP SecurityApproval',    1),
    ('Competitor Normalized Package Name',    2),
    ('NXP Normalized Package Name',    2),
    ('Competitor ZTemperatureGrade',    10),
    ('NXP ZTemperatureGrade',    10);
    -- DDL and sample data population, end
    
    SELECT (
     SELECT FeatureName AS [r] FROM @tbl
     FOR XML PATH(''), TYPE, ROOT('root')
    ).query('
    for $x in distinct-values(/root/r/text())
    let $token := data(concat("[",$x,"]"))
    return 
    if ($x eq (distinct-values(/root/r/text())[last()])[1]) then $token
          else concat($token, ",")
    ').value('.', 'NVARCHAR(MAX)') AS Result;
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.