[英]Select corresponding records from another table, but just the last one
I have 2 tables authors
and authors_sales
我有2个表
authors
和authors_sales
The table authors_sales
is updated each hour so is huge. 该表
authors_sales
每小时都会更新,因此非常大。
What I need is to create a ranking, for that I need to join both tables ( authors
has all the author data while authors_sales
has just sales numbers) 我需要创建一个排名,为此我需要将两个表都
authors_sales
在一起( authors
拥有所有作者数据,而authors_sales
仅具有销售数字)
How can I create a final table with the ranking of authors ordering it by sales? 如何根据作者按销售顺序排列最终排名表?
The common key is the: authorId
公用密钥为:
authorId
I tried with LEFT JOIN but I must be doing something wrong because I get all the authors_sales
table, not just the last. 我尝试了LEFT JOIN,但是我一定做错了,因为我得到了所有
authors_sales
表,而不仅仅是最后一个。
Any tip in the right direction much appreciated 朝正确方向的任何提示都值得赞赏
If you're looking for aggregate data of the sales, you'd want to join the tables, group by the authorId. 如果要查找销售的汇总数据,则需要按authorId分组以合并表。 Something like...
就像是...
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
However (I couldn't distinguish from your question whether the above scenario or next is true), if you're only looking for the max value of the author_sales table (if the data in this table is already aggregated), you can join on a nested query for author_sales, such as... 但是(如果您是上述情况还是下一个情况,我无法区分您的问题),如果您仅查找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
The some_identifier would be how you determine which record is the most recent for author_sales, whether it is a timestamp of when it was inserted or an incremental primary key, however it is set up. some_identifier将是您如何确定哪条记录是author_sales的最新记录,无论是插入记录的时间戳还是增加的主键(但是已设置)。 Depending on if the data in author_sales is aggregated already, one of these two should do it for you...
取决于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.