2017-08-03 11 views
2

と列でグループ、私は同じitemNameに異なる電子メールアドレスに電子メールで送信されてきたitemNameにして電子メールを取得したいです。同じEメールは異なるitemNamesを受け取ることができます。同じitemnameはテーブルの複数の場所に表示できますが、必ずしもidで順序付けされるとは限りません。 ItemNamesは、itemnameで自己結合するのと同じようにユニークです。SQL Serverの:下記のようなテーブルから別の列

私が試した:

を私は、ROW_NUMBERとでグループをクエリの束を試みたなどを有するが、それは権利を取得することはできません。

誰でも手伝っていただけますか?

サンプル・データ: - 複数のメールに送信されたすべてのアイテムを取得するにはCTEを使用して、元のテーブルとそのCTEに参加

declare @t table (id int, itemname nvarchar(50), emailto nvarchar(50)) 

insert into @t 
values (1, 'item1', 'email1') --include 1 & 2 because same item went to different emails 
     , (2, 'item1', 'email2') 
     , (3, 'item2', 'email1') --exclude because even though email1 received an email before, item2 went to a sinle email 
     , (4, 'item3', 'email3') --exclude 4, 5, 6 becuase all item3 went to the same email 
     , (5, 'item3', 'email3') 
     , (6, 'item3', 'email3') 
     , (7, 'item4', 'email6') 
     , (8, 'item4', 'email6') --include 8 & 9, only reason to exclude 7 is to get a distinct list of itemName and email pairs 
     , (9, 'item4', 'email7') 
     , (10, 'item3', 'email3') --exclude 10 becuase all item3 went to the same email, this is the same item from 4, 5, 6 

;with expectedOutput as 
(
    select 
     t.itemname, t.emailto 
    from @t t 
    where 
     t.id IN (1, 2, 8, 9) 
) 
select * 
from expectedOutput 

/* 
Expected output: 
itemname emailto 
item1  email1 
item1  email2 
item4  email6 
item4  email7 

*/ 
+0

プラス1サンプルデータについては、今後も期待される出力を投稿してください。 – TheGameiswar

+0

私は好奇心を持っています。なぜ、ソフトウェア開発者が使用したタグに基づいて適切な名前を知っていても、SQL Serverをmssql :)結果を期待 –

+0

@TheGameiswarがここにSQLスクリプトでもある... –

答えて

3

ここでそれを行うための1つの方法であります:

;WITH Items AS 
(
    SELECT itemname 
    FROM @t 
    GROUP BY itemname 
    HAVING COUNT(DISTINCT emailto) > 1 
) 

SELECT DISTINCT t.itemname, emailto 
FROM @t t 
INNER JOIN Items i ON t.itemname = i.itemname 

結果:

itemname emailto 
item1  email1 
item1  email2 
item4  email6 
item4  email7 
+0

これは、ありがとうございます。 ITEM2は、単一の電子メールに行ってきましたので、email1'ペア - – curious

1

あなたはリットル何であるかと仮定すると、のための電子メールとアイテムのユニークなペアです。

with expectedOutput as 
(select distinct 
    t.itemname, 
    t.emailto 
from @t t), 
steptwo as (
    select tt.itemname, count(distinct tt.emailto) as nemails 
    from expectedOutput tt 
    group by tt.itemname 
) 
select tw.itemname,e.emailto from steptwo tw join expectedOutput e 
on tw.itemname = e.itemname 
WHERE nemails > 1 

我々はすべてそこにしてきた

item1 email1 
item1 email2 
item4 email6 
item4 email7 

を得ました。

+0

それは 'ITEM2を持つべきではありません。 – curious

+0

が修正されました。 upvote良い場合:-)ありがとう。 –

+0

Upvotedそれは動作しますが、他の答えは、よりよい解決策であると。ありがとう。 – curious

関連する問題