在where语句中放入两个不同的日期。

huangapple go评论72阅读模式
英文:

Put two different dates in where statement

问题

我想在SQL语句中查询特定两个月的数据。
这两个月分别是去年的十二月和今年的一月。这需要在SQL语句的where部分完成。(例如22年12月和23年1月)
目前我尝试这样做:

...
SELECT month, year, [...] from table 
WHERE other condition
AND year IN ('2022', '2023')
AND month IN ('12', '1')
...

但是用这个方法我得到的是2022年和2023年的十二月和一月的数据。
如何解决这个问题,只获取2023年的一月数据和2022年的十二月数据?

英文:

I would like to query the data of two specific months in a SQl statement.
These are December from last year and January from this year. This needs to be done in the where part of the SQL statement. (example Dec. 22 and Jan. 23)
Currently I am trying it like this:

...
SELECT month, year, [...] from table 
WHERE other condition
AND year IN ('2022', '2023')
AND month IN ('12', '1')
...

But with this I'm getting the December and January data from 2022 and 2023.
How can I solve this that I get just the January data from 2023 and the December data from 2022?

答案1

得分: 4

SELECT month, year, [...] from table
WHERE other condition
AND (year = '2023' and month = '1'
OR year = '2022' and month = '12')

或者,如果支持:

SELECT month, year, [...] from table
WHERE other condition
AND (year, month) IN (('2023', '1'), ('2022', '12'))

英文:

To get January 2023 and December 2022:

SELECT month, year, [...] from table 
WHERE other condition
  AND (year = '2023' and month = '1'
    OR year = '2022' and month = '12')

Or, if supported:

SELECT month, year, [...] from table 
WHERE other condition
  AND (year, month) IN (('2023', '1'), ('2022', '12'))

答案2

得分: 2

SELECT month, year, [...] from table
WHERE other condition
AND (year * 100 + month) >= 202212
AND (year * 100 + month) <= 202301

英文:
SELECT month, year, [...] from table
WHERE other condition
AND (year * 100 + month) &gt;= 202212
AND (year * 100 + month) &lt;= 202301

huangapple
  • 本文由 发表于 2023年6月15日 16:00:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76480326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定