根据另外两列选择最多一列

时间:2018-01-11 13:46:36

标签: sql-server salesforce

我有一张包含以下数据的表格:

id, foreign_id, contact, asset

对于具有不同foreign_id的同一联系人,有许多条目,我想要做的是获取基于asset的{​​{1}}值。

因此,让我们假设我们有一组这样的数据:

max(id)

我想写一个返回此内容的查询:

id: 1, foreign_id: 15, contact: email@email.com, asset: 1
id: 2, foreign_id: 15, contact: email@email.com, asset: 2
id: 2, foreign_id: 15, contact: email@email.com, asset: 2
id: 3, foreign_id: 14, contact: email@email.com, asset: 3
id: 4, foreign_id: 14, contact: emailTwo@email.com, asset: 1
id: 5, foreign_id: 15, contact: emailTwo@email.com, asset: 5
id: 6, foreign_id: 15, contact: emailTwo@email.com, asset: 12

如您所见,它为每个foreign_id的每个联系人获取最大资产。然后我还希望每行的id: 2, foreign_id: 15, contact: email@email.com, asset: 2, share_number: 2 id: 3, foreign_id: 14, contact: email@email.com, asset: 3, share_number: 1 id: 4, foreign_id: 14, contact: emailTwo@email.com, asset: 1, share_number 1 id: 5, foreign_id: 15, contact: emailTwo@email.com, asset: 12, share_number: 2 与foreign_id排序的特定联系人有关。

这是在Marketing Cloud的SQL Server版本中编写的。我不能使用任何声明或变量。

1 个答案:

答案 0 :(得分:1)

一个选项使用ROW_NUMBER

SELECT id, foreign_id, contact, asset,
    ROW_NUMBER() OVER (PARTITION BY contact ORDER BY id) rn
FROM
(
    SELECT id, foreign_id, contact, asset,
        ROW_NUMBER() OVER (PARTITION BY foreign_id, contact ORDER BY asset DESC) rn
    FROM yourTable
) t
WHERE t.rn = 1;

您的预期输出似乎没有任何特定顺序,但您可以通过在我的查询中添加GROUP BY子句来轻松强加一个。

修改:我在外部查询中添加了对ROW_NUMBER的另一个调用,该调用对共享同一联系人的记录进行编号。我假设排序由id列给出,但我不确定。将ORDER BY id替换为您要使用的列。