[英]How to select just one id from a set of repetitive records in SQL and select only one of the corresponding values
[英]Select corresponding records from another table, but just the last one
我有2個表authors
和authors_sales
該表authors_sales
每小時都會更新,因此非常大。
我需要創建一個排名,為此我需要將兩個表都authors_sales
在一起( authors
擁有所有作者數據,而authors_sales
僅具有銷售數字)
如何根據作者按銷售順序排列最終排名表?
公用密鑰為: authorId
我嘗試了LEFT JOIN,但是我一定做錯了,因為我得到了所有authors_sales
表,而不僅僅是最后一個。
朝正確方向的任何提示都值得贊賞
如果要查找銷售的匯總數據,則需要按authorId分組以合並表。 就像是...
select authors.author_id, SUM(author_sales.sale_amt) as total_sales
from authors
inner join author_sales on author_sales.author_id = authors.author_id
group by authors.author_id
order by total_sales desc
但是(如果您是上述情況還是下一個情況,我無法區分您的問題),如果您僅查找author_sales表的最大值(如果該表中的數據已經聚合),則可以加入一個對author_sales的嵌套查詢,例如...
select author.author_id, t.sales from authors
inner join
(select top 1 author_sales.author_id,
author_sales.sale_amt,
author_sales.some_identifier
from author_sales order by some_identifier desc) t
on t.author_id = author.author_id
order by t.sales desc
some_identifier將是您如何確定哪條記錄是author_sales的最新記錄,無論是插入記錄的時間戳還是增加的主鍵(但是已設置)。 取決於author_sales中的數據是否已經聚合,這兩個之一應該為您完成...
select a.*, sum(b.sales)
from authors as a
inner join authors_sales as b
using authorId
group by b.authorId
order by sum(b.sales) desc;
/* assuming column sales = total for each row in authors_sales */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.