如何从日期中选择一个非空日期 - 如果日期为空,则选择下一个日期

时间:2016-03-16 20:47:07

标签: sql sql-server tsql

我需要从周开始选择一个日期,它必须是星期五。但是,当星期五为空时 - 表示没有输入数据,我必须在同一周找到任何其他日期的数据。有人可以分享他们对如何解决这种情况的看法吗?

如果您在以下数据中看到,在第2周,星期五有空入口,那么必须选择另一天。

Day Weekdate    Data entry dt   Data
1   2/7/2016        
2   2/8/2016        
3   2/9/2016        
4   2/10/2016       
5   2/11/2016       
6   2/12/2016   2/12/2016   500
7   2/13/2016       
1   2/14/2016       
2   2/15/2016       
3   2/16/2016       
4   2/17/2016   2/17/2016   300
5   2/18/2016       
6   2/19/2016   NULL    NULL
7   2/20/2016       
1   2/21/2016       
2   2/22/2016       
3   2/23/2016       
4   2/24/2016       
5   2/25/2016       
6   2/26/2016   2/26/2016   250
7   2/27/2016

2 个答案:

答案 0 :(得分:0)

你可以试试这个

--Not null data
select * from tblData
  where DATEPART(dw,weekDate) = 6 and data is not null

Union

Select data.* from 
  (
    select weekDate 
      from tblData
      where DATEPART(dw,weekDate) = 6 and data is null
  ) nullData --Select Friday with null data
  Cross Apply 
  (
    --Find first record with not null data that is within this week
    Select top 1 * 
      From tblData data
      Where
        data.weekDate between Dateadd(day, -6, nullData.weekDate) and nullData.weekDate
        and data.data is not null
      Order by data.weekDate desc
  ) data

答案 1 :(得分:0)

您可以尝试这样的方法来获取表格中每周输入最新日期(星期五,然后每隔一天)的数据:

SELECT
    Weeks.FirstofWeek,
    Detail.Day,
    Detail.DataEntryDt,
    Detail.Data
FROM
( --master list of weeks
    SELECT DISTINCT DATEADD(DAY,(1-DATEPART(dw,Weekdate)),Weekdate) AS FirstofWeek
    FROM dataTable
) AS Weeks
LEFT OUTER JOIN 
( --detail
    SELECT 
        --order first by presence of data, then by date, selecting Friday first:
        ROW_NUMBER() OVER (PARTITION BY DATEADD(DAY,(1-DATEPART(dw,Weekdate)),Weekdate) ORDER BY CASE WHEN Data IS NOT NULL THEN 99 ELSE 0 END DESC, CASE WHEN [Day] = 6 THEN 99 ELSE [Day] END DESC) AS RowNum,
        [Day],
        DATEADD(DAY,(1-DATEPART(dw,Weekdate)),Weekdate) AS FirstofWeek,
        Weekdate,
        DataEntryDt,
        Data
    FROM dataTable 
) AS Detail
    ON Weeks.FirstofWeek = Detail.FirstofWeek
    AND Detail.RowNum = 1 --get only top record for week with data present