I have a table like this in SQL called Balance
+----+-----------+-------+------+
| id | accountId | Date | Type |
+----+-----------+-------+------+
| PK | FK | Date | Int |
+----+-----------+-------+------+
I need to find the accountId
s that has balance entries in January and March, but not in Febuary. Only in 2018 and Type should be 2.
How would I go about writing my sql select statement?
Thanks
Edit: What's I've done so far: Selecting rows that either
in Jan OR March is not a problem for me.
SELECT AccountId, Date FROM Balance
WHERE Month(Date) in (1,3) AND YEAR(Date) = 2018 AND Type =2
ORDER BY AccountId, Date
But if an AccountId has a single entry, say in January, then this will be included. And that's not what I want. Only if an Account has entries in both Jan and March, and not in Feb is it interesting.
I suspect Group BY
and HAVING
are keys here, but I'm unsure how to proceed
2条答案
按热度按时间i5desfxk1#
I would do this using aggregation:
r55awzrz2#
You can entirely avoid grouping by using exists: