Sql server 如果由于ORDER BY子句中的case语句导致select DISTINCT错误,则ORDER BY项目必须出现在select列表中
我在select中添加了order by列,然后出现了一个错误 如果由于ORDER BY子句中的case语句导致select DISTINCT,则ORDER BY项目必须出现在select列表中 这是针对SQL Server 2012的Sql server 如果由于ORDER BY子句中的case语句导致select DISTINCT错误,则ORDER BY项目必须出现在select列表中,sql-server,Sql Server,我在select中添加了order by列,然后出现了一个错误 如果由于ORDER BY子句中的case语句导致select DISTINCT,则ORDER BY项目必须出现在select列表中 这是针对SQL Server 2012的 DECLARE @SortType VARCHAR(20) = 'lUf' SELECT DISTINCT COUNT(*) OVER () AS Count, nm.NoteID, nm.Title, Descripti
DECLARE @SortType VARCHAR(20) = 'lUf'
SELECT DISTINCT
COUNT(*) OVER () AS Count,
nm.NoteID, nm.Title,
Description, CreatedDate, Createddatetime,
nm.BusinessID, CreatedUser, nm.LastUpdatedDatetime
FROM
PLO.NotesMaster nm with(nolock)
LEFT JOIN
PLO.NoteTags nt ON nm.NoteID = nt.NoteID
WHERE
(nm.Title LIKE '%'+@keyword+'%' OR COALESCE(@keyword ,'')='')
AND (nt.TagID = @TagID OR COALESCE(@TagID, '') = '')
AND (nm.BusinessID = @BusinessID)
AND (nm.CreatedUser = @UserID)
AND (nm.Status != 2)
ORDER BY
Pinned DESC,
(CASE @SortType
WHEN 'lUf' THEN nm.LastUpdatedDatetime
END) DESC,
(CASE @SortType
WHEN 'lul' THEN nm.LastUpdatedDatetime
END) ASC,
(CASE @SortType
WHEN 'az' THEN nm.Title
END) ASC,
(CASE @SortType
WHEN 'za' THEN nm.Title
END) desc
由于您将
selectdistinct
和orderby
与Case
语句一起使用,因此需要将所有orderby列与Case语句一起包含到Select语句中
SELECT DISTINCT
COUNT(*) OVER () AS Count,
nm.NoteID, nm.Title,
Description, CreatedDate, Createddatetime,
nm.BusinessID, CreatedUser, nm.LastUpdatedDatetime,
Pinned DESC,
(CASE @SortType
WHEN 'lUf' THEN nm.LastUpdatedDatetime
END) DESC,
(CASE @SortType
WHEN 'lul' THEN nm.LastUpdatedDatetime
END) ASC,
(CASE @SortType
WHEN 'az' THEN nm.Title
END) ASC,
(CASE @SortType
WHEN 'za' THEN nm.Title
END) desc
FROM
PLO.NotesMaster nm with(nolock)
LEFT JOIN
PLO.NoteTags nt ON nm.NoteID = nt.NoteID
WHERE
(nm.Title LIKE '%'+@keyword+'%' OR COALESCE(@keyword ,'')='')
AND (nt.TagID = @TagID OR COALESCE(@TagID, '') = '')
AND (nm.BusinessID = @BusinessID)
AND (nm.CreatedUser = @UserID)
AND (nm.Status != 2)
ORDER BY
Pinned DESC,
(CASE @SortType
WHEN 'lUf' THEN nm.LastUpdatedDatetime
END) DESC,
(CASE @SortType
WHEN 'lul' THEN nm.LastUpdatedDatetime
END) ASC,
(CASE @SortType
WHEN 'az' THEN nm.Title
END) ASC,
(CASE @SortType
WHEN 'za' THEN nm.Title
END) desc
或
不,你没有:
我在select中添加了order by列,然后出现了一个错误
例如,您尚未添加以下列:
CreatedUser BusinessID Description NoteID Createddatetime CreatedDate
您可以开始注释
选择中的列,以查看查询何时开始工作。I仅对order by子句使用3列。即,LastUpdateDateTime和title。我添加了这3个columns@alenantony您需要添加所有列-SELECT语句中引用的所有列必须在ORDER BY
子句中指定-只需将它们添加到当前列之后,它们不会造成任何伤害。
CreatedUser BusinessID Description NoteID Createddatetime CreatedDate