在2个不同的栏中满足2个条件

时间:2018-11-14 13:36:26

标签: sql sql-server

我正在尝试在需要满足非常具体条件的地方运行查询:

  1. 销售代码已全部
  2. 商品已设置原始价格标记
  3. 商品的价格没有设置原始价格标志,与设置了原始价格标志的价格相同
  4. 未设置原始价格标记的价格必须在带有原始价格标记的价格之后创建

当前,我正在使用以下查询来获取所需的信息;

select [item no_], [variant code],[unit price including vat], 
[original price], [Starting Date], [Ending Date] from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000'

这是示例结果: Click here

  

1表示设置了原始价格标记,0表示未设置

此查询中需要的结果是仅显示以下两个: Click here

2 个答案:

答案 0 :(得分:0)

我假设您正在使用SQL Server,如当前查询语法所建议的那样。

如果可以,则可以使用lag()

select sp.*
from (select sp.*,
             lag([original price]) over (partition by [item no_] order by [Starting Date]) as prev_price
      from [Sales Price] sp
      where [Sales Code] = 'all'
     ) sp
where ([original price] = 1 or prev_price = 1);

答案 1 :(得分:0)

让我知道是否需要我解释;否则很简单。

select a.* 
from (
select [item no_]
, [variant code]
,[unit price including vat]
, [original price]
, [Starting Date]
, [Ending Date] 
,Column_Test = case when ( [original price] = 1 and [original price] = 0 ) and ([Starting Date]<[Ending Date]) then 1 else 0 end
from [Sales Price]
where [Sales Code] = 'all'
and [Ending Date] = '1753-01-01 00:00:00.000' 
) a
where Column_Test = 1
相关问题