declare @userid int
set @userid=9846
SELECT TOP 10
tagid,
[Description]
FROM tagsuggestion
WHERE tagid IN (SELECT **DISTINCT** TOP 10 tagid
FROM (SELECT ulpt.tagid,
createddate
FROM userlocationposttag ulpt
WHERE ulpt.UserID=@userid
UNION ALL
SELECT ult.tagid,
createddate
FROM userlocationtag ult
WHERE ult.UserID=@userid
UNION ALL
SELECT upt.tagid,
createddate
FROM userprofiletag upt
WHERE upt.UserID=@userid
) T
ORDER BY createddate DESC)
The above query is error ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
.but if i remove DISTINCT this query runs
I want to ensure the distinctness and i also want to keep the sort order by createddate DESC
one of my associated post is
Okay, so we only care about each tag based on it’s most recent created date, so we can structure the inner query as:
And then we can wrap that in another subselect, and apply the top ten:
And we no longer need distinct (because
GROUP BYandMAXalready ensured that each tag only appears once)