A
A
AstralProjection2019-11-29 09:40:54
SQL
AstralProjection, 2019-11-29 09:40:54

How to correctly select data by date range with subquery?

5de0bb44c8a60927370012.jpeg
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

2 answer(s)
K
Konstantin Tsvetkov, 2019-11-29
@AstralProjection

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')

R
Ruslan., 2019-11-29
@LaRN

You can try like this:

SELECT Users.UserID 
  FROM Transactions   
  JOIN Users
    on Users.ManagerId = Transactions.Detail
 GROUP BY Users.UserID 
HAVING MAX(Transactions.CreationDate) < '2018-11-01'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question