【发布时间】:2017-08-03 10:37:45
【问题描述】:
从下面的表格中,我想获取 itemName 和电子邮件,其中相同的 itemName 已通过电子邮件发送到不同的电子邮件地址。相同的电子邮件可以接收不同的 itemName。相同的 itemname 可以出现在表格中的多个位置,它们并不总是按 id 排序。 ItemNames 是唯一的,因为可以通过 itemname 自行加入。
我试过了:
我尝试了一堆带有 row_number、group by、have 等的查询,但无法正确处理。
有人可以帮忙吗?
样本数据:
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
*/
【问题讨论】:
-
样本数据加 1,今后也请发布预期输出
-
先生现在很好奇我很好奇为什么即使您根据使用的标签知道正确的名称,软件开发人员也将 SQL Server 称为 mssql? :)
-
@TheGameiswar 预期结果也在此处的 sql 脚本中...
-
@ZoharPeled:我的意图是要求用户发布预期的总输出。我认为这样会更好
-
@TheGameiswar 我也虽然不是很清楚,但当我将代码复制到 rextester 并且可以立即看到预期的输出与我自己的查询输出时,它再次非常有帮助。不过,我认为您是正确的,并且所需的输出也应该以表格的形式出现在问题中。
标签: sql-server tsql sql-server-2016