3

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

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值。对于上述情况,我希望:

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

我可以做 a GROUP BYMAX为每一列取 ,但它只是按字母顺序排列的最高值,并没有考虑CustomerID在内。

SQL小提琴

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

此外,这是在 Exact Target 中编程的,这意味着不支持某些 SQL 关键字,尤其是不支持变量、临时表和游标。

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

4

1 回答 1

3

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

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
于 2014-05-12T18:50:48.903 回答