首页 > 解决方案 > 需要基于某些条件的sql查询

问题描述

select CardCode, ItemCode, T0.DocDate, ''[CustomerType]  from OINV T0 inner Join INV1 T1 on T1.DocEntry = T0.DocEntry and year(T0.DocDate) >= year(getdate()) -4 

我又添加了一个名为“CustomerType”的列,看起来像“ New ”、“ Existing ”、“ One more Product

根据docdateitemcode列检查的条件:

  1. 例如,现在是 2020 年,如果 2019 年没有销售,则 customertype 为 = '<strong>New' else ' Existing ' 。需要根据 ' CardCode ' 列检查

  2. 例如:那些客户类型“现有”我需要检查他们之前是否购买过商品代码,如果他们购买了,那么客户类型保持为“现有”,如果不应该反映为“另一种产品”。需要根据 ' ItemCode ' 列检查

样本结果集:

CardCode    ItemCode    DocDate     CustomerType
C-SGD-2748  V0796-0038  2017-01-24 
C-SGD-1489  V0796-0066  2020-06-10 
C-SGD-2748  V0796-0106  2019-01-15  
C-SGD-1489  V0796-0130  2019-05-17 
C-SGD-2652  V0805-0001  2016-12-08 

标签: sqlsql-serversql-server-2016

解决方案


您可以使用case和窗口函数:

select t.*,
       (case when min(docdate) over (partition by cardcode) >= '2020-01-01'
             then 'New'
             when row_number() over (partition by cardcode, itemcode order by docdate) > 1
             then 'existing'
             else 'one more product'
        end) as customertype

我发现这些类型相当混乱。但是,这似乎正是您所描述的。


推荐阅读