【发布时间】:2019-01-25 05:45:30
【问题描述】:
我在select中添加了按列排序,然后出现错误
如果SELECT DISTINCT由于order by子句中的case语句,ORDER BY项必须出现在选择列表中
这适用于 SQL Server 2012
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
【问题讨论】:
标签: sql-server