简体   繁体   中英

Select corresponding records from another table, but just the last one

I have 2 tables authors and authors_sales

The table authors_sales is updated each hour so is huge.

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)

How can I create a final table with the ranking of authors ordering it by sales?

The common key is the: 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.

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. 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...

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. Depending on if the data in author_sales is aggregated already, one of these two should do it for you...

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 */

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