Reputation: 826
I have this query that I am working on for a one time report. Basically what I am trying to do is find all the records where there are more than two transactions by a single account ID last month. I know it is probably something easy, my mind is just blanking.
SELECT streaming_transactions.account_id,
streaming_transactions_detail.transactions_description,
streaming_transactions_detail.transactions_detail_id,
streaming_transactions_detail.transactions_id,
streaming_transactions_detail.transactions_detail_amount,
streaming_transactions_detail.detail_type,
streaming_transactions_detail.products_id,
streaming_transactions_detail.products_levels_id,
streaming_transactions_detail.subscriptions_id,
streaming_transactions_detail.subscriptions_payment_options_id,
streaming_transactions_detail.modified
FROM streaming_transactions_detail
INNER JOIN streaming_transactions ON streaming_transactions_detail.transactions_id = streaming_transactions.transactions_id
WHERE streaming_transactions.charged = 1
AND streaming_transactions.timestamp_inserted > '2009-09-01 00:00:00'
AND streaming_transactions.account_id IN (
SELECT account_id
FROM streaming_transactions_detail
WHERE modified > '2009-09-01 00:00:00'
AND count(account_id) > 1)
AND streaming_transactions_detail.transactions_description LIKE '%Service Subscription%'
ORDER BY streaming_transactions.account_id DESC
Upvotes: 1
Views: 100
Reputation: 75095
I think you're almost there. The subquery to get the transaction Ids is off, however
SELECT account_id
FROM streaming_transactions_detail
WHERE modified > '2009-09-01 00:00:00'
AND count(account_id) > 1)
-- Should be something like
SELECT account_id, COUNT(account_id)
FROM streaming_transactions_detail
WHERE modified > '2009-09-01 00:00:00'
GROUP BY account_id
HAVING count(account_id) > 1)
[unrelated] I'll throw in an unsolicited hint about style.
By using table aliases, you can improve the readabilty of the query. This can be done by optionally adding "AS xyz" where xyz is some short but mnemonic name, unique to this query, you can use xyz wherever in the query where you would use the long_named_table.
For example:
FROM streaming_transactions_detail AS D
and then
SELECT streaming_transactions.account_id,
streaming_transactions_detail.transactions_description,
streaming_transactions_detail.transactions_detail_id,
...
Can become (optionally, i.e. the "streaming_transactions_detail." still works too)
SELECT D.account_id,
D.transactions_description,
D.transactions_detail_id,
...
Upvotes: 3