SQL Server:按列分组,另一列

时间:2017-08-03 10:37:46

标签: sql-server tsql sql-server-2016

从下面的表中,我想获取itemName和电子邮件,其中相同的itemName已通过电子邮件发送到不同的电子邮件地址。同一封电子邮件可以接收不同的itemNames。相同的itemname可以出现在表中的多个位置,它们并不总是按id排序。 ItemNames是唯一的,因为它可以通过itemname自行加入。

我试过了:

我尝试了一堆查询,包括row_number,分组,等等,但无法正确查找。

有人能帮忙吗?

示例数据:

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

*/

2 个答案:

答案 0 :(得分:3)

这是一种方法 - 使用CTE获取发送到多个电子邮件的所有项目,然后将该cte与原始表格连接:

;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

答案 1 :(得分: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

我们都去过那里。