当前位置: 代码迷 >> Sql Server >> group by 两个参数如何简化
  详细解决方案

group by 两个参数如何简化

热度:15   发布时间:2016-04-24 09:25:40.0
group by 两个参数怎么简化
本帖最后由 guize 于 2014-12-26 14:45:39 编辑
条件是 
当[Frent_BrandId]不为空的时候,查找[Frent_BrandId]不重复的数据,
联合[Frent_BrandId]为空的时候Frent_UserId不重复的数据
select [Frent_BrandId] from [Eble_ForRent]  where [Frent_BrandId] is not null group by  [Frent_BrandId]
union all
select [Frent_UserId] from [Eble_ForRent]  where [Frent_BrandId] is  null group by  [Frent_UserId]


这SQL语句可以简化不?
------解决思路----------------------
两个互斥条件,最后同一个字段输出。lz 最后 union all 输出的里面可能会有重复,如果不需要重复,直接用Union吧。 


------解决思路----------------------
select DISTINCT ISNULL([Frent_BrandId],[Frent_UserId]) AS Id
  from [Eble_ForRent]

如果只返回一个字段的不重复值,也可以用 DISTINCT,不用 GROUP BY。
------解决思路----------------------

select distinct case when [Frent_BrandId] is not null then [Frent_BrandId]
                     when [Frent_BrandId] is null then [Frent_UserId] end 'Frent_BrandId'
 from [Eble_ForRent] 
  相关解决方案