首页 文章

SQL选择(1月和3月)的日期,而不是2月

提问于
浏览
0

我在SQL中有一个这样的表叫做Balance

+----+-----------+-------+------+
    | id | accountId | Date  | Type |
    +----+-----------+-------+------+
    | PK | FK        | Date  | Int  |
    +----+-----------+-------+------+

我需要找到在1月和3月有余额条目的accountIds,但在2月份有 not . 仅在2018年,Type应为2 .

我将如何编写我的sql select语句?

谢谢

编辑:到目前为止's I'已经做了什么:选择1月或3月的行对我来说不是问题 .

SELECT AccountId, Date FROM Balance
WHERE Month(Date) in (1,3) AND YEAR(Date) = 2018 AND Type =2
ORDER BY AccountId, Date

但是,如果一个AccountId只有一个条目,比如一月份,那么这将包括在内 . 这不是我想要的 . 只有当一个账户在1月和3月都有参赛作品,而不是在2月份参赛时才有意思 .

我怀疑 Group BYHAVING 是这里的关键,但我不确定如何继续

1 回答

  • 3

    我会使用聚合来做到这一点:

    select b.accountid
    from balance b
    where date >= '2018-01-01' and date < '2019-01-01'
    group by b.accountid
    having sum(case when month(date) = 1 then 1 else 0 end) > 0 and  -- has january
           sum(case when month(date) = 3 then 1 else 0 end) > 0 and  -- has march
           sum(case when month(date) = 2 then 1 else 0 end) = 0  -- does not have february
    

相关问题