【问题标题】:Need the SQL query based on the Condition需要基于Condition的SQL查询
【发布时间】:2020-07-21 12:00:54
【问题描述】:

这是我的 SQL 查询

select CardCode, ItemCode, DocDate, DocYear from OINV

我需要添加更多名为 customertype

的列
  1. New => 如果没有基于去年的购买交易。 2020去年是2019,2019去年是2018,2018去年是2017,2017去年是2016等等。那么客户类型是“new”。

  2. OneMoreProduct => 商品代码基于每个客户商品代码历史 2020、2019、2018、2017 等等,如果第一次购买此商品代码。那么客户类型是“onemoreproduct

  3. Existing => 如果以上两个条件不符则为“existing

我需要根据这三种类型写一个案例。

【问题讨论】:

  • 向我们展示一些示例表数据和预期结果,全部为格式化文本(不是图像)。即minimal reproducible example.
  • 和你previous one的问题基本一样
  • 上一个问题我没有提出适当的要求。对不起

标签: sql sql-server sql-server-2016


【解决方案1】:

在 SQL Server 2008 中,可用的窗口函数是有限的。一种方法使用case 表达式:

select o.*,
       (case when not exists (select 1
                              from oinv o2
                              where o2.cardcode = o.cardcode and
                                    o2.docyear = o.docyear - 1
                             )
             then 'New'
             when row_number() over (partition by cardcode, itemcode order by date) = 1
             then 'OneMoreProduct'
             else 'Existing'
        end) as customertype
from oinv o;

【讨论】:

  • 对不起我的sql是2016
  • 当 row_number() over (partition by CardCode, ItemCode order by date) = 1 or when row_number() over (partition by CardCode, ItemCode order by docdate)
  • @VignaHariKarthik 。 . .这也适用于 SQL Server 2016。
  • 我需要在这个语句中添加一个 where 条件我怎样才能实现它?当 row_number() over (partition by cardcode, itemcode where oniv.itemgroupcode =10 order by date) = 1.跨度>
  • @VignaHariKarthik 。 . .将where 添加到外部查询。我怀疑你在子查询中需要它,但你可能也需要它。
【解决方案2】:

您可能希望为列使用 CASE 语句。

您的规则并不明显,因为您没有发布示例 DDL 和示例数据。 如果您想要一个好的答案,然后发布 DDL,插入示例数据......然后提出问题。见:https://stackoverflow.com/help/minimal-reproducible-example

但这是一个通用的答案。

select CardCode, ItemCode, DocDate, DocYear ,
    [customertype] =
    CASE    
        WHEN 1=1 Then 'new'
        WHEN 2=2 Then 'onemoreproduct'
        ELSE 'existing'
    END
FROM OINV

您将根据需要“编写”WHEN 语句。

【讨论】:

  • 您好,我知道情况,我没有样品要检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多