【问题标题】:SQL - Left Join Into New Columns without Creating DuplicatesSQL - 左连接到新列而不创建重复项
【发布时间】:2017-03-20 16:15:22
【问题描述】:

我有一个基于 customerid 的客户表 (tcustomers)。我有另一个表,其中包含购买历史记录 (tpurchasehist) 和客户 ID。我正在尝试将 twp 列添加到我的第一个表中 - 一个标记为“黄金会员?”如果购买列中的条目类似于“%Gold%”,则值为“是”,另一个在购买列中的最新行类似于客户的“%Purchased%”或“%Returned%”。我的问题是我似乎不太清楚如何在不创建任何重复项的情况下进行左连接,因为每个客户 ID 有多个购买条目。

SELECT tcustomers.custid 'Customer ID',
       tcustomers.custname 'Name',
       CASE
           WHEN th.purchases LIKE '%Purchased%' THEN 'Customer Made a Purchase'
           WHEN th.purchases like '%Returned%' THEN 'Customer Made a Return'
       END 'Recent Activity',
       CASE
           WHEN th.purchases LIKE '%Gold%' THEN 'Yes'
       END 'Gold Member?'
FROM tcustomerss
LEFT JOIN (
    SELECT DISTINCT th.custid, purchases, updated
    FROM tpurchasehist
    WHERE purchases LIKE '%Purchased%'
       or purchases like '%Returned%'
       or purchases like '%Gold%')
) th ON tcustomers.custid = th.custid

【问题讨论】:

  • 您需要告诉我们您想要处理每个客户有多个购买事件的情况的逻辑。此问题不会自动解决。
  • 您的示例是无效的标准 SQL。您使用的是哪个 DBMS?

标签: sql


【解决方案1】:

您可以尝试窗口函数,首先获取记录(包括重复项),然后对获取的记录使用partition by(将之前的查询视为内部查询),然后获取使用 first 窗口函数获得所需的输出。

【讨论】:

    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 2013-01-14
    • 2022-01-22
    • 2021-10-25
    • 2013-03-02
    • 2014-07-21
    • 2014-07-29
    • 2017-07-02
    相关资源
    最近更新 更多