2

我有一个查询项,它按格式为'YYYYMM'. 到目前为止,我已经硬编码了这个值[DateCol] = '201406'Detail filters获取当前的月份和年份记录。但我想动态地改变这个值。下个月它应该按“201407”过滤记录。我如何实现这一目标?[DateCol]我通过拖动a来尝试这个Detail filters

[DateCol] = extract(year, current_date) + extract(month, current_date)

但是它返回了一个错误:

UDA-SQL-0460 The operation "equal" is invalid for the following combination of data types: Character and Integer

请指导

4

3 回答 3

3

另一个公式

[DateCol] = cast(extract(year, current_date) * 100 + extract(month, current_date) as varchar(6))
于 2014-06-27T16:53:07.053 回答
2

The simplest solution is to create what I call a 'month key' which is an integer representation of a year and month. You can then convert this to a char for comparison. It's actually quite simple:

extract(year, current_date) * 100 + extract(month, current_date)

Multiplying any number by 100 results in adding two zeroes to the end. The current year is 2014 so 2014 times 100 equals 201400. You are then free to add the month to get a 'month key'. 201400 + 6 = 201406. You can then convert this integer to a char and make your comparison. The final filter expression becomes:

[DateCol] = cast(extract(year, current_date) * 100 + extract(month, current_date), char(6))

Note: The technique of making integer 'keys' for dates can be extended to days as well and has many applications, namely sorting. The following expression will give you an integer 'day key' which retains the numerical order and hierarchy of the original date:

extract(year, current_date) * 10000 + extract(month, current_date) * 100 + extract(day, current_date)
于 2014-06-27T17:05:48.830 回答
1

两个问题。DateCol 的数据类型是字符。extract 函数返回整数。其次,您没有使用提取正确构建 YYYYMM。按照您的方式,您将年份提取为数字,然后将月份添加到其中。你最终会得到像'201406' = 2020 这样的东西,这是行不通的。因此,您需要转换两个提取物并将它们连接起来:

[DateCol] = cast(extract(year, current_date) as varchar(4) 

+ cast (extract(month, current_date) as varchar(2))

编辑:实际上,它可能会比这更复杂。6 月份的提取不会返回 06,只会返回 6。因此,您需要确定该提取是一个字符还是两个字符。如果是一个,你需要在施法后在前面加上一个“0”。确切的语法将取决于您的数据库,但如下所示:

[DateCol] = cast(extract(year, current_date) as varchar(4)
+ case when cast (extract(month, current_date) as varchar(2) = 1
    then '0' + cast (extract(month, current_date) as varchar(2)
  else cast (extract(month, current_date) as varchar(2)
end
于 2014-06-27T16:34:56.290 回答