【问题标题】:SQL Server : group by column with another columnSQL Server:按列与另一列分组
【发布时间】: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


【解决方案1】:

这是一种方法 - 使用 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

【讨论】:

    【解决方案2】:

    假设您正在寻找的是独特的电子邮件和项目对。

    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
    

    我们都去过那里。

    【讨论】:

    • 它不应该有 item2 - email1 对,因为 item2 转到了单个电子邮件。
    • 赞成,因为它有效,但另一个答案是更好的解决方案。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 2020-12-06
    相关资源
    最近更新 更多