查询有错误

时间:2017-02-08 21:35:08

标签: sql sql-server

我的查询有问题,我的表格看起来像this

作为查询的结果,我希望当天的月初知道如果是1月1月1日开始。我们从本月的最后几天开始,我们知道月初是上个月的结尾加一。 我的查询如下:

select * 
from (select top 11 case when replace(convert(varchar, EndMonth, 111), '/','-') = replace(convert(varchar, getdate(), 111), '/','-') then replace(convert(varchar, EndMonth, 111), '/','-') else replace(convert(varchar, DATEADD(day,1,EndMonth), 111), '/','-') end as inicio  
from EndMonths 
where EndMonth >= convert(date,getdate()) 
and Year between  DATEPART (year, getdate()) 
and ( (DATEPART (year, getdate())+1)) or id = (select top 1 id-1 from P_materials.dbo.dia_cierre_fiscal where Year= DATEPART (year, getdate()) and Month(EndMonth) = Month(getdate()) order by EndMonth desc) 
order by EndMonth)a 
union 
select case when GETDATE()<=(select EndMonth from EndMonths where Year=2017 and NameMonth='Jenuary') then convert(varchar,YEAR(GETDATE()))+'-01-01' else '' end

它在2月份之前一直运行,只是2月它没有给我相同的结果。

3 个答案:

答案 0 :(得分:0)

以下是您的数据的小型复制品,以及将其转换为开始日期/结束日期对的查询:

WITH YourTable AS 
(
SELECT Label,D
FROM (
VALUES 
('Jan',CAST('2017-02-03' AS DATE)),
('Feb',CAST('2017-03-03' AS DATE)),
('Mar',CAST('2017-03-31' AS DATE)),
('Apr',CAST('2017-05-05' AS DATE)),
('May',CAST('2017-06-02' AS DATE))
) T(Label, D)
) 

SELECT ED.Label,
(SELECT DATEADD(d,1,MAX(D)) FROM YourTable WHERE D < ED.D) StartDate,
ED.D EndDate
FROM 
YourTable ED

要使用它,您只需插入所需的日期:

WITH YourTable AS 
(
SELECT Label,D
FROM (
VALUES 
('Jan',CAST('2017-02-03' AS DATE)),
('Feb',CAST('2017-03-03' AS DATE)),
('Mar',CAST('2017-03-31' AS DATE)),
('Apr',CAST('2017-05-05' AS DATE)),
('May',CAST('2017-06-02' AS DATE))
) T(Label, D)
) 

SELECT *
FROM
(
    SELECT ED.Label,
    (SELECT DATEADD(d,1,MAX(D)) FROM YourTable WHERE D < ED.D) StartDate,
    ED.D EndDate
    FROM 
    YourTable ED
) ATable
WHERE GETDATE() BETWEEN StartDate AND EndDate

请注意以后的任何问题:屏幕截图都可以,但是一些实际的SQL代码(即我上面提到的值代码)可以让我们快速使用您的数据,让每个人都能更轻松,更快速地完成任务。

答案 1 :(得分:-1)

你为什么这么复杂?

select cast(datepart(m, getdate()) as varchar(2)) + '/1/'+ cast (datepart(year, getdate()) as varchar (4))

答案 2 :(得分:-1)

您可以根据提供的日期获取当月的第一个和最后一个日期:

DECLARE @MyDate DATE = '2017-02-01'

SELECT   DATEFROMPARTS(YEAR(@MyDate),MONTH(@MyDate),01) AS Start_Month
        ,DATEADD(DAY, -1, DATEFROMPARTS(YEAR(@MyDate),MONTH(@MyDate) + 1,01)) AS End_Month