简体   繁体   中英

Get count for the max date [MYSQL]

i have this schema EER图

I have to find the count of customers that in their latest account (capital*) balance (they might have multiple accounts), balance_value is over than 1.000.000

*capital: balance_type ='Capital'

I guess my Query for that returns wrong results and it its inefficient

SELECT COUNT(DISTINCT customer.customer_id) AS customers
    FROM balance INNER JOIN account ON balance.account_id = account.account_id
    INNER JOIN contract ON account.contract_id = contract.contract_id
    INNER JOIN customer ON customer.customer_id = contract.customer_id
    WHERE  balance.balance_type like '%Capital%' AND balance.balance_value > 1000000
    ORDER BY balance.balance_date DESC

i guess that i need some help :S

Download sample data (move Data folder to C:/) and script to create the schema https://drive.google.com/file/d/0BxVNamixm4W2SHVadndtWkNBajg/view?usp=sharing

what is your query result?

what kind of 'correct' result did you expect?

fyi,

group by customer_id will make it faster than distinct does

if you know the exact capital word, would better using EQUAL TO / = rather than LIKE (= is faster than LIKE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM