2017-08-28 10 views
1

は、私はまた、これらのテーブル参加のお客様とタグテーブル

Customers 
    CustomerNumber date 
    001    8/1/2017 
    002    8/2/2017 
    003    8/3/2017 

    Tags 
    Index Tag Description 
    1  NEW New customer 
    2  OTHER Some other tag 

    Customers_Tags 
    TagIndex CustomerNumber 
    1   001 
    1   002 
    2   002 
    2   003 

どのように私は、単一のクエリでは、タグ1とすべての顧客を得ることができ、それらの顧客が持っている任意の他のタグを持っていますか?だから、タグ1のgetを探している場合:

customer tag date 
001   1  8/1/2017 
002   1  8/2/2017 
002   2  8/2/2017 

答えて

2

その顧客は、インデックス1のタグを持っている場合、すべての顧客とタグを取得するためにexists()を使用して:

select ct.customernumber, ct.tagindex, c.date 
from customers c 
    inner join customers_tags ct 
    on c.customernumber = ct.customernumber 
where exists (
    select 1 
    from customers_tags i 
    where i.customernumber = ct.customernumber 
    and i.tagindex = 1 
) 

またはin()使用:

select ct.customernumber, ct.tagindex, c.date 
from customers c 
    inner join customers_tags ct 
    on c.customernumber = ct.customernumber 
where c.customernumber in (
    select i.customernumber 
    from customers_tags i 
    where i.tagindex = 1 
) 
+0

ありがとうございます、完璧な作品です。これに顧客のタグ数を追加する簡単な方法はありますか? –

+1

@PatrickSchomburg 'select ...、CustomerTagCount = count(*)over(partition by ct.customernumber)'のようなウィンドウ関数として 'count()'を使うことができます。 – SqlZim

+1

ありがとう、ありがとう。 –

関連する問題