我有一个带有日期和其他列的表格。日期为所有工作日,节假日和周末除外。我需要从表格中选择每周数据(或每个星期一的数据,如果星期一是假期,则选择星期二。下一行将是星期一的数据,依此类推。)
Example table columns and data:
Date Rate StockQty
2018/08/31 22 25
2018/09/04 24 25
2018/09/05 23 24
2018/09/06 19 21
2018/09/07 25 22
2018/09/10 21 21
I need to select data such that the result will be:
Date Rate StockQty
2018/08/31 22 25
2018/09/04 24 25
2018/09/10 21 21
它每周选择一行。 9/3是星期一和节假日,因此选择星期二日期,然后选择下周的星期一日期。
我试图按DatePart进行分区,但整个星期都无法完成。
答案 0 :(得分:0)
您可以遵循以下逻辑:
select t.*
from (select t.*,
row_number() over (partition by extract(year from date), extract(week from date) order by date asc) as seqnum
from t
) t
where seqnum = 1;
日期功能可能因数据库而异。这使用ANSI / ISO标准功能。
答案 1 :(得分:0)
这在SQL Server中应该可以使用:
SELECT date,Rate,StockQty FROM
(SELECT
date,
Rate,
StockQty,
ROW_NUMBER() OVER(PARTITION BY YEAR(date),DATENAME(WK,Date) ORDER BY day(date))cnt
FROM
#temp
)m
WHERE
cnt = 1
答案 2 :(得分:0)
create table #Date_rate
(
date smalldatetime,rate int,stockQty int
)
Insert into #Date_rate
select '2018/08/31', 22 , 25 union
select '2018/09/04', 24 , 25 union
select '2018/09/05', 23 , 24 union
select '2018/09/06', 19 , 21 union
select '2018/09/07', 25 , 22 union
select '2018/09/10', 21 , 21
select
a.date
,a.rate
,a.stockQty
from(
select
*
,dense_rank() over(partition by datepart(WEEK,date) order by datepart(WEEKDAY,date) asc) as SekectedDay
from #Date_rate
) a where SekectedDay=1