将周数转换为周的第一天

时间:2016-08-02 15:35:26

标签: sql sql-server date week-number

我有一个包含日期的列的表。我的目标是按星期分组,使用一周的第一天(星期一)。目前,我只按星期编号进行分组,我无法弄清楚如何将周数转换为星期开始日期。目前的代码:

SELECT 
        DATEPART(week, CONVERT_TIMEZONE('UTC', 'America/Denver', fact_completed_offer_engagements.verified)) AS "fact_completed_offer_engagements.verified_date",
        COUNT(DISTINCT CASE WHEN fact_completed_offer_engagements.activated IS NOT NULL THEN fact_completed_offer_engagements.customer_offer_id ELSE NULL END) AS "fact_completed_offer_engagements.shopping_list_placements"
FROM public.fact_completed_offer_engagements AS fact_completed_offer_engagements
LEFT JOIN public.offers AS offers ON fact_completed_offer_engagements.offer_id = offers.id
LEFT JOIN public.campaigns AS campaigns ON offers.campaign_id = campaigns.id
LEFT JOIN public.contracts AS contracts ON campaigns.contract_id = contracts.id

  WHERE 
    (campaigns.id = ?)
                OR campaigns.id = ?
group by 1
ORDER BY 1
limit 1000

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

您可以在这里查看:https://stackoverflow.com/a/38601630/5089204

请注意,您正在使用特定于文化的逻辑。一周的第一天是星期一,但不是到处都是......

使用@@DATEFIRST计算与此相关的文化独立日期

DECLARE @testDate DATETIME=GETDATE();
SELECT @testDate - (@@DATEFIRST + DATEPART(WEEKDAY,@testDate)) % 7 + 1; 

结果总是在给定日期之前的星期日。最后添加+2,即可获得星期一。

更新

您可能希望将结果转换为DATE以摆脱时间组件......

答案 1 :(得分:0)

您可以使用以下序列生成和聚合CTE计算周开始日期。只需在周数上加入您的查询,并根据您的要求更改开始日期。

-- Set fist day of week as Monday
SET DATEFIRST 1;

;WITH CTE_Nums AS (
              SELECT    ROW_NUMBER() OVER (ORDER BY ob.object_id) AS Num
              FROM      sys.all_objects AS ob
             ),
CTE_WeekBegin AS (
SELECT DATEPART(WEEK, DATEADD(DAY, Num, '2016-01-01')) AS WeekNo, MIN(DATEADD(DAY, Num, '2016-01-01')) AS Date
FROM CTE_Nums
GROUP BY DATEPART(WEEK, DATEADD(DAY, Num, '2016-01-01'))
)
SELECT wb.Date, ...
FROM ...
INNER JOIN CTE_WeekBegin wb ON wb.WeekNo = xx.xx;