Answer the question
In order to leave comments, you need to log in
How to correctly select data by date range with subquery?
There is a base of users, their wallets and transactions.
You need to find users whose last transaction was in October 2018, and the Users.ManagerId value is written in the details of this transaction.
I wrote a query with WHERE EXISTS, but I don't know how to add a condition that there were no transactions after October 2018. Please tell me how you can optimize, or is it better to leave a request for some other structure ..?
I also assume that the date range in the format '2018-10-01 00:00:00' can be specified somehow more simply, I focus on the Transactions.CreationDate - datetime format.
SELECT
UserID
FROM
Users
WHERE
EXISTS
(
SELECT
TransactionID
FROM
Transactions
WHERE
Transactions.Detail = Users.ManagerId
AND Transactions.CreationDate BETWEEN '2018-10-01 00:00:00' AND '2018-10-31 23:59:59'
)
Answer the question
In order to leave comments, you need to log in
SELECT Users.UserID, Users.ManagerId
FROM Users
INNER JOIN Wallets ON Users.UserID = Wallets.UserID
INNER JOIN WalletSections ON Wallets.WalletID = WalletSections.WalletID
INNER JOIN Transactions ON WalletSections.WalletSectionID = Transactions.WalletSectionID
GROUP BY Users.UserID, Users.ManagerId
HAVING (MAX(Transactions.CreationDate) BETWEEN '2018-10-01 00:00:00' AND '2018-10-31 23:59:59')
SELECT Users.UserID
FROM Users
INNER JOIN Wallets ON Users.UserID = Wallets.UserID
INNER JOIN WalletSections ON Wallets.WalletID = WalletSections.WalletID
INNER JOIN Transactions ON WalletSections.WalletSectionID = Transactions.WalletSectionID
WHERE (Transactions.Detail = Users.ManagerId)
GROUP BY Users.UserID
HAVING (MAX(Transactions.CreationDate) BETWEEN '2018-10-01 00:00:00' AND '2018-10-31 23:59:59')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question