SQL Query和case语句通过连接两个表来显示多个条目

时间:2017-08-04 11:05:08

标签: sql select sql-server-2012

这是两个表的示例,我想创建一个视图作为最终结果。有两个表作为视图的输入,一个具有位置ID的国家,另一个具有位置名称,我想加入它们然后做一个用单个条目替换多个计数的情况。 任何帮助表示赞赏。

Here is the screenshot of how tables look like, Table Entity and Table Location as input tables to the view

我首先考虑从实体表中获取多个位置ID的计数,然后创建一个选择Case语句但没有用,这是草稿代码。

select
    Country, count(locationid),
    case LocationName
        when Cnt > 1 then 'Mulitple offices'
        when Cnt = 0 then 'Unknown Location'
        else LocationName
    end
from 
    Entity 
group by 
    Country

更新: 我刚刚制作了一个SQLFiddle(非常方便)并且实现了@Gordon和@ P.Eh的两个解决方案,但有一些问题。具体见下文评论

2 个答案:

答案 0 :(得分:0)

你似乎想要这样的东西:

select e.Country, count(l.locationId),
       (case when count(l.locationId) > 1 Then 'Mulitple offices'
             when count(l.locationId) = 0  then 'Unknown Location'
             else max(l.LocationName)
        end)
from Entity e left join
     Location l
     on e.locationId = l.locationId
group by e.Country;

答案 1 :(得分:0)

i think this is what you wanted:
- when location_id in location table is NULL or 0 then 'Unknow location'

select
    COU.Country,
    case 
        when COU.pleace is null OR COU.pleace=0 then 'Unknow location'
        when COU.number_of_pleaces > 1 then 'Multiple offices'
        else coalesce(LOC.Location_name,'cound not math location')
    end as [location name]
from
    (   select country,
            sum(1) as number_of_pleaces,
            max(Location_id) as pleace
        from @entity
        group by country
    ) COU
    left join
    @location LOC
        on LOC.Location_id = COU.pleace
        and COU.number_of_pleaces = 1