2017-11-28 7 views
2

を取得私は選択する必要が3列テーブル内のすべてのグループの相互の値(SQL Serverの)

ID(主キー)、masCode(masterCode)とdetCode(detailCode)

を持つテーブルを持っています私はこのデータを持っている場合たとえば、すべてのmasCodeグループ

で繰り返されdetCodes:

+----+---------+----------+ 
| id | masCode | detCode | 
+----+---------+----------+ 
| 1 | 111  | 1  | 
| 2 | 111  | 5  | 
| 3 | 222  | 2  | 
| 4 | 222  | 5  | 
| 5 | 222  | 1  | 
| 6 | 223  | 5  | 
| 7 | 223  | 6  | 
| 8 | 223  | 1  | 
+----+---------+----------+ 

結果はこのことだろう10

+----+---------+----------+ 
| id | masCode | detCode | 
+----+---------+----------+ 
| 1 | 111  | 1  | 
| 2 | 111  | 5  | 
| 4 | 222  | 5  | 
| 5 | 222  | 1  | 
| 6 | 223  | 5  | 
| 8 | 223  | 1  | 
+----+---------+----------+ 

私は動的なクエリでこれを行うことができると思う、これを行うには良い方法はありますか? ありがとう

答えて

2

ここには1つの方法があります。

declare @masCode int = (select count(distinct masCode) from YourTable) 

select * 
from yourTable 
where detCode in (select detCode 
       from YourTable 
       group by detCode 
       having count(detCode) = @masCode) 

ONLINE DEMO

1

これを試してみてください:

;with _countedDetCodes as (
    select 
     *, 
     -- number of masCodes for particular detCode 
     count(1) over (partition by detCode) as masCodeCnt 
    from yourTable 
) 
select 
    Id, masCode, detCode 
from _countedDetCodes 
where 
    masCodeCnt = (select count(distinct masCode) as [Value] from yourTable) 
0

動的照会(テキストとして書かれており、SQLで実行されている、すなわちクエリは '実行' 命令)、一般的に悪い考えです。

execute ('select * from NotExistingTable') 

理由はいくつかあります。 あなたのエディタは、クエリのエラーを追跡するために(少なくともクエリ実行前ではなく)あなたを助けることができません。クエリが複雑になると、これが問題になります。

もう1つの問題は、SQL Serverがクエリについて何も想定できないということです。つまり、 です。これは通常、パフォーマンスを低下させる最適化された実行計画を実行できません。

あなたが探しているものはかなり簡単です。 ここに1つの解決策があります。ここ

;with nonuniques as (
select masCode from [YourTable] 
group by masCode 
having count(*) > 1 
) select id, masCode, detCode from [YourTable] t 
    inner join nonuniques n on n.masCode = t.masCode 
0

はあなたのための迅速かつ容易なソリューションです:

drop table if exists #temp 

create table #temp 
(
id  int, 
masCode int, 
detCode int 
) 

insert into #temp values 
(1,111,1) 
,(2,111,5) 
,(3,222,2) 
,(4,222,5) 
,(5,222,1) 
,(6,223,5) 
,(7,223,6) 
,(8,223,1) 

select * 
from #temp a 
where a.detCode in (
     select t.detCode 
     from #temp t 
     group 
     by  t.detCode 
     having(count(mascode)) > 1 
     ) 
関連する問題