SQL Server If else exist语句在选择查询中

fumotvh3  于 2023-02-07  发布在  其他
关注(0)|答案(1)|浏览(140)

这里有三个表,我希望查询选择哪个过滤器将在7未来几天内到期。

我在Filter表和FilterChange表中分别有两列filterExpfilterExpCustom,如果第二列不为空,则第一列为默认值。所有过滤器都有一个按天计算的过期值,但在某些情况下,有些用户希望更改自己的过期值。因此,他们可以为特定客户和过滤器设置filterExpCustom
以下是一些实际值,可以更好地理解:

过滤器

INSERT [Filter] ([filterId], [filterName], [filterExp]) 
VALUES (1, N'pp', 6)
INSERT [Filter] ([filterId], [filterName], [filterExp]) 
VALUES (2, N'Carbonate', 5)
INSERT [Filter] ([filterId], [filterName], [filterExp]) 
VALUES (3, N'Carbon Block', 5)
INSERT [Filter] ([filterId], [filterName], [filterExp]) 
VALUES (4, N'Carbon Post', 12)
INSERT [Filter] ([filterId], [filterName], [filterExp]) 
VALUES (5, N'Mineral', 12)

过滤器更换

INSERT [FilterChange] ([filterChnageId], [customerId], [filterId], [customerDeviceId], [filterChangeDate], [filterExpCustom]) 
VALUES (186, 3, 2, 65, CAST(N'2023-01-31' AS Date), 7)
INSERT [FilterChange] ([filterChnageId], [customerId], [filterId], [customerDeviceId], [filterChangeDate], [filterExpCustom]) 
VALUES (187, 3, 5, 65, CAST(N'2023-01-31' AS Date), NULL)
INSERT [FilterChange] ([filterChnageId], [customerId], [filterId], [customerDeviceId], [filterChangeDate], [filterExpCustom]) 
VALUES (188, 2, 3, 66, CAST(N'2023-02-01' AS Date), 10)
INSERT [FilterChange] ([filterChnageId], [customerId], [filterId], [customerDeviceId], [filterChangeDate], [filterExpCustom]) 
VALUES (189, 2, 3, 66, CAST(N'2023-02-01' AS Date), NULL)

下面是我可以从现在到下一个7天获得过期过滤器的查询:

CREATE PROCEDURE [dbo].[FilterExpirationGetList]
  @userName BIGINT
AS
  DECLARE @InNextDays int
BEGIN
    SET @InNextDays = 7

  SELECT f.filterId,f.filterName, f.filterExp,
    fc.customerId, fc.customerDeviceId, fc.filterChangeDate, fc.filterExpCustom,
    c.fName, c.lName, c.cMobile, c.userName
   FROM FilterChange fc INNER JOIN
     Filter f  ON fc.filterId = f.filterId  INNER JOIN
     Customer c ON c.CustomerId = fc.customerId
   WHERE c.userName = @userName AND
    DATEADD(DAY, DATEPART(DAY, GETDATE()) 
    - DATEPART(DAY, DATEADD(DAY,f.filterExp,fc.filterChangeDate)), 
    DATEADD(DAY,f.filterExp,fc.filterChangeDate))
          BETWEEN CONVERT(DATE, GETDATE()) 
           AND CONVERT(DATE, GETDATE() + @InNextDays); 
END

我的查询的问题是,如果filterExpCustom有某个值,我不知道如何选择过期的过滤器,但如果没有,则必须在查询中计算filterExp

hgb9j2n6

hgb9j2n61#

可能类似于这样,您使用ISNULL来获得正确的日期扩展:

select *
from customer c
inner join FilterChange fc
 ON fc.customerID = fc.CustomerID
INNER JOIN Filter f
 ON f.filterID = fc.filterID
WHERE DATEADD(DAY, ISNULL(fc.filterExpCustom,filterExp), filterChangeDate) BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 7, GETDATE())

我不知道你怎么处理过滤器在今天之前过期的客户。你的设计似乎缺少一种标志,表明过滤器的变化是“取代”另一个变化。
或者,您可以只获取过期日期未来7天的过滤器类型的最新filterchange。

相关问题