5

I have two tables in sql server and i wanna select and join some data from these table.the first tables have some customer like:

---------------
customer   id   
Dave       1    
Tom        2     
---------------

and second table i table of purchases that includes list of last purchases with cost and which customer bought that Product:

------------------
product    date       customer id
PC         1-1-2000   1
phone      2-3-2000   2
laptop     3-1-2000   1
------------------

i wanna select first table (customers info) with last date of their purchases! i tried left join but that doesn't give me last purchases becuase customer id is not unique in second table! how can i do this function with SQL server query? Regards

4

3 回答 3

2

如果您只想要最大日期,请使用聚合。我会left join为没有购买的客户推荐一个:

select c.customer, c.id, max(p.date)
from customers c left join
     purchases p
     on c.id = p.customer_id
group by c.customer, c.id;
于 2016-07-16T22:16:37.383 回答
1

使用not exists条款赢得胜利!

select c.customer, p.*
from   Customer as c
inner  join Purchase as p
on     p.customer_id = c.id
where  not exists (
       select 1
       from Purchase as p2
       where p2.customer_id = p.customer_id
       and p2.date > p.date
       )
于 2016-07-16T21:58:51.097 回答
1

我认为您可以使用内部联接和分组方式

select table1.customer, table1.id, table.max(date) 
from  table1 
inner join table2 on table1.id = table2.id 
group by table1.customer, table1.id
于 2016-07-16T22:03:42.783 回答