2014-05-12 163 views
3

对于每个电子邮件地址具有多行的数据库,我想按每个电子邮件地址进行分组,并为每个电子邮件地址输入“最新”信息。分组依据与基于另一列的聚合

Email  Col1 Col2 Col3 Col4 CustomerID 
======= ==== ==== ==== ==== ========== 
[email protected] a  a  a  null 1 
[email protected] null b  b  null 2 
[email protected] null null c  null 3 

我想借此非空值最高CustomerID。对于以上情况,我会期望:

Email  Col1 Col2 Col3 Col4 
======= ==== ==== ==== ==== 
[email protected] 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 

另外,这正中的确切目标程序,这意味着some SQL keywords are unsupported,最显着的变量,临时表和游标不支持。

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

+0

我花了一段较长的时间试图比写的问题找出一个标题。如果您有更好的方式来总结问题,请随意更改标题。 –

+0

如何在字符串类型值上使用'MAX'? – Rahul

+0

@Rahul它只是按字母顺序获得最大价值。无论如何,这不是我想要的,因为我希望它只是具有最大CustomerID的非空值。 –

回答

3

如果我正确理解你的问题,我认为你需要多次加入表格本身。像这样的东西应该使用common 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 
+0

如果精确目标支持公用表表达式,这似乎可行。不幸的是,它没有:http://help.exacttarget.com/en-US/documentation/exacttarget/interactions/activities/query_activity/#section_6 –

+0

@WillEddins - 你不需要使用CTE,只是使用它作为一个子查询来代替。更新小提琴:http://sqlfiddle.com/#!3/35b27/8 – sgeddes

+0

工程很好,谢谢! –