"activity" is a bit field. I need to set it to true if one of the rows with this client_id has value true
SELECT c.client_id, u.branch_id, a.account_id, activity
FROM Clients c INNER JOIN
accounts a ON c.id=a.client_id INNER JOIN uso u ON a.uso_id = u.uso_id,
(SELECT MAX(CONVERT(int,accounts.activity)) as activity, client_id
FROM accounts GROUP BY client_id) activ
WHERE activ.client_id = c.id
This query executes about 2 minutes. Please help me to optimize it.
Seems activity
field is a BIT
and you cannot do a MIN
or MAX
on it.
Instead of this, use TOP
:
SELECT c.client_id, u.branch_id, a.account_id,
(
SELECT TOP 1 activity
FROM accounts ai
WHERE ai.client_id = c.id
ORDER BY
activity DESC
)
FROM clients c
JOIN accounts a
ON c.id = a.client_id
JOIN uso u
ON a.uso_id = u.uso_id
Create an index on accounts (client_id, activity)
for this to work fast.
You may want to read this article:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With