我需要从当前月到下个月的表格中选择数据。但我的数据中没有日期列。日期分为三个部分 - CalDay,CalMonth和CalYear。
我在下面尝试过查询:
SELECT CustomerName, CalDay, CalMonth, CalYear, RequiredHours
FROM [DLSizingDB].[dbo].[SMTRequiredHours]
WHERE
CalYear >= (SELECT YEAR(GETDATE())) AND
CalYear <= (SELECT YEAR(DATEADD(MONTH,12,CURRENT_TIMESTAMP))) AND
CalMonth >= (SELECT MONTH(GETDATE()))
AND SiteCode = 'MX01'
ORDER BY CustomerName
仅选择2016年12月之前的数据。我也需要选择2017年1月。怎么做到这一点?
样本数据
CustomerName CalDay CalMonth CalYear RequiredHours
"ACFG" 1 2 2016 10
"AZS" 1 3 2016 20
"AZW" 1 4 2016 20
"AZG" 1 5 2016 20
"AZJ" 1 6 2016 20
"AZL" 1 1 2017 20
答案 0 :(得分:0)
也许这样的事情会起作用......
SELECT CustomerName, CalDay, CalMonth, CalYear, RequiredHours
FROM [DLSizingDB].[dbo].[SMTRequiredHours]
WHERE
SiteCode = 'MX01' AND
(
(CalYear = YEAR(GETDATE()) AND CalMonth >= MONTH(GETDATE()))
OR
(CalYear = YEAR(GETDATE()) + 1 AND CalMonth < MONTH(GETDATE()))
)
ORDER BY CustomerName
年份是当前年份和月份大于当前月份或年份是明年,月份小于当月。
答案 1 :(得分:0)
此声明也考虑了CalDay。这将选择日期在[current_date,current_date +一年]范围内的所有条目。
SELECT CustomerName, CalDay, CalMonth, CalYear, RequiredHours
FROM [DLSizingDB].[dbo].[SMTRequiredHours]
WHERE
SiteCode = 'MX01' AND (
calyear=YEAR(GETDATE()) AND (calmonth>MONTH(GETDATE()) OR calmonth=MONTH(GETDATE()) AND calday>=DAY(GETDATE())) OR
calyear=YEAR(GETDATE())+1 AND (calmonth<MONTH(GETDATE()) OR calmonth=MONTH(GETDATE()) AND calday< DAY(GETDATE()))
)
ORDER BY CustomerName;
在SQL Server 2012+中,您可以使用DATEFROMPARTS
:
SELECT CustomerName, CalDay, CalMonth, CalYear, RequiredHours
FROM [DLSizingDB].[dbo].[SMTRequiredHours]
WHERE
SiteCode = 'MX01' AND
DATEFROMPARTS(calyear,calmonth,calday) BETWEEN CAST(GETDATE() AS DATE) AND CAST(DATEADD(DAY,-1,DATEADD(YEAR,1,GETDATE())) AS DATE)
ORDER BY CustomerName;