需要基于某些条件的sql查询

sxpgvts3  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(306)
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”
根据docdate和itemcode列检查的条件:
e、 g.现在是2020年,如果2019年没有销售,那么customertype为'new'或'existing'。需要根据“cardcode”列进行检查
例如:那些客户类型“existing”我需要检查他们是否在之前购买了itemcode如果他们购买了,那么customertype仍然是“existing”如果不是应该反映为“one more product”。需要根据“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
neekobn8

neekobn81#

你可以用 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

我觉得这些类型比较混乱。然而,这似乎正是你所描述的。

相关问题