Incorrect syntax next to the keyword "Distinct"

In my query System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'Distinct' the following error appears. I searched Google but did not find a useful solution as per my request. My request is

 SqlCommand myCommand = new SqlCommand("select ItemId,Distinct Size from ItemTilesSizes ", myConnection); 

The name of my table is ItemTilesSizes and has two columns

 ItemId Size 1 8x13 1 8x12 5 8x10 5 8x12 5 8x13 8 10x10 8 4x4 9 8x12 14 8x13 15 8x10 15 24x24` 
+4
source share
4 answers

DISTINCT should be the first, but it will give you all the distinct pairs of ItemId and Size . Is this what you need, or were you looking for something else?

+9
source

Distinct needed immediately after SELECT

 SELECT DISTINCT ItemId, Size FROM ItemTilesSizes 

If you want it to apply only to Size , you need GROUP BY , and aggregate to determine which of the possible matching ItemId values ​​should be returned (the example below returns the largest)

 SELECT MAX(ItemId) AS ItemId, Size FROM ItemTilesSizes GROUP BY Size 

Although from the explanation in the comment, I would simply return this as the only set of column results and perform any necessary concatenation in your application. If you must do this in SQL, you can use the XML PATH

 SELECT STUFF((SELECT ',' + LEFT(ItemId, 10) FROM ItemTilesSizes WHERE Size = '8x12' FOR XML PATH('')), 1, 1, '') 
+3
source

The SQL DISTINCT command used with the SELECT keyword retrieves only unique data records, depending on the list of columns that you specify after it. so you need to use the DISTINCT command as shown in the following query

"select DISTINCT ItemId, Size from ItemTilesSizes"

This will allow you to select unique records from your table in a combination of both ItemID and Size.

+2
source

using

 select distinct ItemId, ... 
+1
source

Source: https://habr.com/ru/post/1394872/


All Articles