【问题标题】:Group By with aggregates based on another columnGroup By 与基于另一列的聚合
【发布时间】:2014-06-30 05:56:58
【问题描述】:

对于每个电子邮件地址多行的数据库,我想按每个电子邮件地址分组,获取每个电子邮件地址的“最新”信息。

Email      Col1    Col2    Col3   Col4    CustomerID
=======    ====    ====    ====   ====    ==========
a@a.com    a       a       a      null    1
a@a.com    null    b       b      null    2
a@a.com    null    null    c      null    3

我想取 CustomerID 最高的 non-null 值。对于上述情况,我希望:

Email      Col1    Col2    Col3   Col4
=======    ====    ====    ====   ====
a@a.com    a       b       c      null

我可以做一个GROUP BY,为每一列取MAX,但这只是按字母顺序排列的最高值,不考虑CustomerID

SQL Fiddle

SELECT EmailAddress, MAX(FirstName), MAX(LastName), MAX(Gender), MAX(Birthday), MAX(Country)
FROM CustomerInfo
GROUP BY EmailAddress

此外,这是在 Exact Target 中编程的,这意味着 some SQL keywords are unsupported,最值得注意的是不支持变量、临时表和游标。

鉴于这些限制,是否有可能获得预期的结果?

【问题讨论】:

  • 我花了更长的时间试图找出一个标题而不是写这个问题。如果您有更好的方法来总结问题,请随意更改标题。
  • 如何在字符串类型值上使用MAX
  • @Rahul 它只是按字母顺序获得最大值。无论如何,这不是我想要的,因为我希望它只是具有最大 CustomerID 的非空值。
  • 一定要为空吗?空的怎么样?
  • @Mihai 如果没有值,则应该为空,因为理论上空字符串可能是有效值。

标签: sql sql-server sql-server-2005 group-by exacttarget


【解决方案1】:

如果我正确理解了您的问题,我认为您需要多次将表格加入到自身中。这样的事情应该使用common table expression 来获取每列不是null 的每个列的max 客户ID。然后它连接回自身以获取值:

with cte as (
  select email, 
      max(case when col1 is not null then customerid end) maxcustomerid1,
      max(case when col2 is not null then customerid end) maxcustomerid2,
      max(case when col3 is not null then customerid end) maxcustomerid3,
      max(case when col4 is not null then customerid end) maxcustomerid4
    from yourtable
    group by email
)
select t.email,
  t1.col1,
  t2.col2, 
  t3.col3,
  t4.col4
from cte t
  left join yourtable t1 on t.email = t1.email and t.maxcustomerid1 = t1.customerid
  left join yourtable t2 on t.email = t2.email and t.maxcustomerid2 = t2.customerid
  left join yourtable t3 on t.email = t3.email and t.maxcustomerid3 = t3.customerid
  left join yourtable t4 on t.email = t4.email and t.maxcustomerid4 = t4.customerid

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-22
  • 2020-06-06
  • 2021-02-03
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多