如何在两列

时间:2016-08-30 10:59:03

标签: sql-server

我有一个SQL Server数据库表Inventory,其中包含两列我感兴趣的hospital_idlocation_id列。他们每个人都可以分别重复。

我想找出hospital_id以有序方式有多个location_id的<{p}}

例如,这些是我的专栏:

enter image description here

输出应为:

enter image description here

7 个答案:

答案 0 :(得分:3)

<强>更新

作为戈登查询的替代方案,您可以稍微修改@JuergenD和我最初给出的答案:

SELECT hospital_id
FROM yourTable
GROUP BY hospital_id
HAVING COUNT(*) - COUNT(DISTINCT location_id) >= 1
ORDER BY hospital_id

任何位置一式两份的医院的总计数大于DISTINCT计数。

答案 1 :(得分:3)

我相信您需要重复hospital_id / location_id对。我不确定你为什么只输出hospital_id,但你可以做

select hospital_id
from t
group by hospital_id, location_id
having count(*) > 1;

答案 2 :(得分:1)

select hospital_id, count(location_id) as locationcount from tab2
group by hospital_id
having count(location_id) > 1
order by hospital_id

答案 3 :(得分:0)

SELECT a.hospital_id 
FROM (
    SELECT  hospital_id, 
            COUNT(location_id)
            location_count 
    FROM Inventory 
    GROUP BY hospital_id 
    HAVING COUNT(location_id) > 1 
) a ORDER BY hospital_id

答案 4 :(得分:0)

还有一种方法:

SELECT TOP 1 WITH TIES hospital_id --, location_id --if you need
FROM Inventory
ORDER BY 
    CASE WHEN ROW_NUMBER() OVER (PARTITION BY hospital_id, location_id ORDER BY location_id) = 2 THEN 0 ELSE 1 END ASC

它会显示至少有2个重复行的所有hospital_id

答案 5 :(得分:0)

您看起来更像医院和更多医院和地点吗?

;with cte as (
select hospital_id,'' locaation_id, count(location_id) as locationcount from tab2
group by hospital_id
having count(location_id) > 1

union all

select hospital_id, location_id, count(*) as cnt from tab2
group by hospital_id, location_id
having count(*) > 1
)
select * from cte order by hospital_id 

在CTE的选择列表中,只有在需要时才能选择hospital_id

答案 6 :(得分:0)

select  hospital_id,
        location_id 
into #temp1 
from inventory 
where hospital_id in (
        select hospital_id 
        from inventory 
        group by hospital_id 
        having count(hospital_id)>1)
group by hospital_id,location_id 

select hospital_id 
from #temp1 
group by hospital_id 
having count(hospital_id)>1