日期发布SQL第一天的月份交叉

时间:2015-08-14 07:42:02

标签: sql-server datetime

这是我在第27年的问题周显示2个日期,因为月份的交叉发生它会产生另一个月的第1天, 我只想在每个实例中显示第一次出现这种情况

Datetime----------------|WeekofYear ------|FirstDayOfMonth
2015-06-29 00:00:00.000 |27 --------------|2015-06-01 00:00:00.000
2015-07-01 00:00:00.000 |27 --------------|2015-07-01 00:00:00.000
CREATE TABLE #weekonweek
(
[Datetime] datetime,
[WeekofYear] int,
[FirstDayOfMonth] datetime
)

INSERT INTO #weekonweek

SELECT 
min(c.Datetime),
c.WeekOfYear
,c.FirstDayOfMonth

FROM Calendar c
WHERE YEAR = 2015
and WeekOfYear = 27
GROUP BY WeekOfYear ,c.FirstDayOfMonth
SELECT * FROM #weekonweek


CREATE TABLE #subtable
(
[Datetime] datetime,
[WeekofYear] int,
[FirstDayOfMonth] datetime,
)

INSERT INTO #subtable

SELECT 
c.Datetime,
w.WeekOfYear,
min(w.FirstdayofMonth)
FROM Calendar c
LEFT JOIN #weekonweek w on c.WeekOfYear  = w.WeekofYear
WHERE YEAR = 2015
and c.WeekOfYear = 27
and w.FirstDayOfMonth <w.FirstDayOfMonth
group by c.Datetime,
w.WeekOfYear
SELECT * FROM #subtable
DROP TABLE #subtable
DROP TABLE #weekonweek

1 个答案:

答案 0 :(得分:0)

SELECT DR.DivNo
    ,p.[ProductCode]
    ,p.ProductClass
    ,p.EmpNo
    ,[Description]
    ,[CGNo]
    ,[SCGNo]
    ,dr.Retail
    ,bd.[Buying Director]
INTO #Product
FROM [PRODUCT] p
LEFT JOIN [DIVRETAIL] DR ON p.ProductCode = DR.ProductCode
WHERE dr.ValidTo IS NULL
    AND dr.DivNo NOT LIKE '8__'
GROUP BY DR.DivNo
    ,p.[ProductCode]
    ,p.ProductClass
    ,p.EmpNo
    ,bd.[Buying Director]
    ,[Description]
    ,[CGNo]
    ,[SCGNo]
    ,dr.Retail



SELECT TOP 1000 [Datetime]
        ,[FirstDayOfWeek]
        ,[FirstDayOfMonth]
        ,s.NoOfStores
        ,s.DivNo
    INTO #stores
    FROM [Calendar] c
    LEFT JOIN Stores s ON c.FirstDayOfMonth = s.Validfrom
    WHERE DATETIME = firstdayofweek