MariaDB中获取日回报率最高TOP2产品的SQL实现问询
Solution for Getting Top 2 Products with Highest Daily Return on Latest Date
Hey Carol, let's fix this up for your MariaDB 10.1.39 setup! Your current query calculates daily returns but doesn't focus on the latest date or handle sorting/limiting correctly. Here's a tailored solution:
Step-by-Step Explanation & SQL Query
We need to:
- Match each product's latest day close value with its previous day's close
- Calculate daily return using your specified formula
- Filter only the latest date's records
- Sort returns from highest to lowest and pick the top 2
SELECT t1.id, t1.date, t1.product_name, t1.close, ROUND((t1.close - t2.close) / t2.close, 9) AS daily_return FROM prices t1 INNER JOIN prices t2 ON t1.product_name = t2.product_name AND t2.date = DATE_SUB(t1.date, INTERVAL 1 DAY) WHERE t1.date = (SELECT MAX(date) FROM prices) -- Target only the most recent date ORDER BY daily_return DESC LIMIT 2;
Breakdown of the Query:
- JOIN Clause: We join the
pricestable to itself (t1for current day,t2for previous day) usingproduct_nameto ensure we're comparing the same product, andDATE_SUBto link each date with the day before it. - WHERE Filter:
(SELECT MAX(date) FROM prices)dynamically grabs the latest date in your table, so this works even if you add newer data later. - Return Calculation: We use
ROUNDto match the decimal precision in your expected output (9 decimal places). - Sort & Limit:
ORDER BY daily_return DESCsorts returns from highest to lowest, thenLIMIT 2gives us the top 2 products.
Why This Is Better Than Your Current Query:
- Your original query includes records from the last two days (due to
DATE >= DATE(NOW()) - INTERVAL 1 DAY), while this one focuses only on the latest date's data. - The JOIN approach is more efficient than nested subqueries for large datasets, as it avoids running a subquery for every single row.
Expected Output:
| id | date | product_name | close | daily_return |
|---|---|---|---|---|
| 4 | 2019-08-07 00:00:00 | Product 2 | 874 | 0.182679296 |
| 1 | 2019-08-07 00:00:00 | Product 1 | 806 | -0.179226069 |
内容的提问来源于stack exchange,提问作者Carol.Kar
相关产品推荐
相关产品推荐

