在我使用SQL Server的代码中,我比较了两个月之间我确定确切日期的数据。我正在尝试查找某些列中的值是否会在一些不同的情况下发生变化。这部分工作,但我想要做的是,使我不必总是回去改变日期,每次我想获得我期待的结果。这可能吗?我至今是:如何在WHERE子句中动态调用日期而不是硬编码?
with
dates as (
select distinct
d.Date
from Database d
WHERE
d.Date IN (
SELECT MAX(Date)
FROM Database
group by YEAR(Date), MONTH(Date)
)
)
select
case
when (t1.[Mapping Status] = '0' and t2.[Mapping Status]= '0') or (t1.[Mapping Status] = '1' and t2.[Mapping Status] = '1')
then 'No Change'
when t1.[Mapping Status] = '0' and t2.[Mapping Status]= '1'
then 'Newly Changed in Status'
when t1.[Mapping Status] = '1' and t2.[Mapping Status] = '0'
then 'Resolved'
when t1.[Mapping Status] is null and t2.[Mapping Status] = '1'
then 'New Resolved'
when t1.[Mapping Status] is null and t2.[Mapping Status] = '0'
then 'New Not Resolved'
when t2.[Mapping Status] is null and t1.[Mapping Status] = '1'
then 'Instance Retired'
when t2.[Mapping Status] is null and t1.[Mapping Status] = '0'
then 'Instance Not Retired'
else
'Status Remains Missing'
end as [Status Change]
, *
from Database t1
full join Database t2 on t1.Column = t2.Column
left join dates d on d.Date = t1.Date
where t1.date like '01-31-2017'
and t2.date like '02-28-2017'
order by [Status Change]
我的想法是,添加一个WITH子句,我可以得到的maxDate然后,而不是调用确切一天下来,我在那里我可以使用类似:
where t1.date like max(getdate()-1)
and t2.date like max(getdate())
但它给我一个聚合错误。无论如何,我可以将这个日期问题简单化吗?在此先感谢
编辑
好吧,我想澄清一下。在我的发言,我有:
select distinct
d.Date
from Database d
将返回:
+------+-------------+
| | Date |
+------+-------------|
| 1 | 01-06-2017 |
| 2 | 01-13-2017 |
| 3 | 01-20-2017 |
| 4 | 01-27-2017 |
| 5 | 02-03-2017 |
| 6 | 02-10-2017 |
| 7 | 02-17-2017 |
| 8 | 02-24-2017 |
| 9 | ........ |
+------+-------------+
如果我选择该语句并执行,它会从我的表如上图所示只返回日期。我想要做的是能够得到从这些日期值中提取的sql,并比较从一个月的最后日期值到下一个月的最后日期值。实质上,它应该将日期8的值与日期4的值进行比较,但它应该足够动态,以便可以在没有太多修补的情况下为任何两个日期执行相同的操作。
你可以在其中接受,这将简化其参数的存储过程这个包起来。你总是需要提供日期值_无论你描述一些逻辑自动派生它们_这是什么类型的数据库? –
对不起,它位于microsoft sql server内。我编辑我的帖子来澄清。提供日期值的问题在于,我需要在一年中的每个星期都这样做,并且代码会变得太长。 – programr
应该date1 BETWEEN begindate和enddate在此工作? – maSTAShuFu