sql - 需要基于某些条件的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 ”
根据docdate和itemcode列检查的条件:
例如,现在是 2020 年,如果 2019 年没有销售,则 customertype 为 = '<strong>New' else ' Existing ' 。需要根据 ' CardCode ' 列检查
例如:那些客户类型“现有”我需要检查他们之前是否购买过商品代码,如果他们购买了,那么客户类型保持为“现有”,如果不应该反映为“另一种产品”。需要根据 ' 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
解决方案
您可以使用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
我发现这些类型相当混乱。但是,这似乎正是您所描述的。
推荐阅读
- java - 比较布尔值时,JUnit Mockito 在 assertEquals 中总是返回 false
- vhdl - VHDL 对象已使用但未声明。
- datetime - 基于日期长生不老药在主机之间切换
- swift - 使用计算机视觉为室内导航系统绘制大面积地图的解决方案是什么?
- php - 我在哪里可以检查错误日志中的 500 错误?
- c++ - 返回 int 中可被 2 整除的所有数字的总和 c++
- java - 扫描仪不要求输入,抛出无此类元素异常 - 多个扫描仪
- docker - 在多个端口而不是指定端口中运行的 Docker 容器
- java - jsp中如何计算文本输入到文本框中的次数?
- menu - Umbraco Maganav - 添加上传图片的选项