我有一个SQL查询,我正在使用distinct
语句
CREATE proc SProc_SelectPhotographersByLocation
@locationID varchar(500)
as
begin
DECLARE @TEST varchar(1000)
DECLARE @SQLQuery AS NVARCHAR(1000)
SET @TEST = @locationID
SET @SQLQuery = 'select distinct ContributerSubCategoryMapping.ContributorID, PhotographerContributors_tbl.* from ContributerSubCategoryMapping
left outer join PhotographerContributors_tbl on PhotographerContributors_tbl.ContributorId=ContributerSubCategoryMapping.ContributorID
left outer join tbl_City on tbl_City.CityID=PhotographerContributors_tbl.Location
where
PhotographerContributors_tbl.Location IN('+ @locationID +') and PhotographerContributors_tbl.IsActive=''1'' order by Newid()'
EXECUTE(@SQLQuery)
end
当我在该查询上使用NEWID()
时,我的查询出错了。
错误是
如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。
请帮我解决这个问题
答案 0 :(得分:5)
使用group by
代替distinct
。一种方法是明确列出列:
select csm.ContributorID, pc.col1, pc.col2, . . .
from ContributerSubCategoryMapping csm left outer join
PhotographerContributors_tbl pc
on pc.ContributorId = csm.ContributorID left outer join
tbl_City c
on c.CityID = pc.Location
where pc.Location IN ('+ @locationID +') and pc.IsActive=''1''
group by csm.ConstributorId, pc.col1, pc.col2, . . .
order by Newid();
但是,我不明白查询。表ContributerSubCategoryMapping
和tbl_City
似乎没有被使用。那么为什么不这样做?
select pc.*
from PhotographerContributors_tbl pc
where pc.Location IN ('+ @locationID +') and pc.IsActive=''1''
order by Newid();