【问题标题】:how to change week num to iso week in SQL如何在 SQL 中将周数更改为 iso 周
【发布时间】:2022-11-03 00:09:57
【问题描述】:

我的数据如下所示:

CustomerID Trans_date
C001 01-sep-22
C001 04-sep-22
C001 14-sep-22
C002 03-sep-22
C002 01-sep-22
C002 18-sep-22
C002 20-sep-22
C003 02-sep-22
C003 28-sep-22
C004 08-sep-22
C004 18-sep-22

使用此查询处理后:

WITH CTE (customerID,FirstWeek,RN) AS (
        SELECT customerID,MIN(DATEPART(week,tp_date)) TransWeek,
        ROW_NUMBER() over(partition by customerID ORDER BY DATEPART(week,tp_date) asc ) FROM all_table
        GROUP BY customerID,DATEPART(week,tp_date)
    ) 
    
    SELECT CTE.customerID, CTE.FirstWeek,  
         (select TOP 1 (DATEPART(week,c.tp_date))   
            from all_table c 
                where c.customerID = CTE.customerID AND DATEPART(week,C.tp_date) > CTE.FirstWeek 
                    )   SecondWeek 
    FROM CTE  
    WHERE RN = 1

结果是这样的

CustomerID firstweek secondweek
C001 36 37
C002 36 39
C003 36 40
C004 37 39

但在 excel 中使用 weeknum 时,结果将是合适的。但我希望结果是等周格式,看起来像这样

CustomerID firstweek secondweek
C001 35 37
C002 35 37
C003 35 39
C003 36 37

【问题讨论】:

标签: sql sql-server database


【解决方案1】:

已经创建了一个小小提琴来帮助enter link description here

据我了解,我只会使用按客户分组的周的最小值和最大值

【讨论】:

猜你喜欢
  • 2021-12-13
  • 2019-08-20
  • 1970-01-01
  • 2015-01-11
  • 2018-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-15
相关资源
最近更新 更多