从另一个表中按列的一个表顺序选择列

时间:2017-03-21 06:44:44

标签: sql sql-server

我有两张桌子:

Customer_Master

 CUSTOMER_ID    CUSTOMER_NAME 
 ----------------------------
   1             Test1
   2             Test2

Ticket_Master

 TICKETID   CUSTOMER_ID     UPDATEDATE
 --------------------------------------------------
    1           1           2017-03-03 00:00:00.000
    2           1           2017-03-20 20:09:31.000
    3           2           2017-03-20 20:11:00.000
    4           2           2017-03-20 20:15:29.000

我需要使用表1中所有元素的结果按Ticket_Mater的更新时间排序。将结果连接到重复行,而我需要来自Customer_Master的不同行。

SELECT 
    a.CUSTOMER_ID, MAX(b.UPDATEDATE)
FROM 
    customer_master AS a 
INNER JOIN
    Ticket_master AS b ON a.CUSTOMER_ID = b.CUSTOMERID 
GROUP BY 
    a.CUSTOMER_ID 
ORDER BY 
    MAX(b.UPDATEDATE) DESC

以上查询按更新返回订单,但不返回customer_master的所有元素。

SELECT  
    a.*, b.UPDATEDATE
FROM 
    customer_master AS a
INNER  JOIN 
    Ticket_master AS b ON a.customer_id = b.customerid
ORDER BY 
    b.UPDATEDATE desc

此查询返回Ticket_master中的重复行。

请帮忙。每一个帮助都会得到高度赞赏。

2 个答案:

答案 0 :(得分:2)

由于Ticket_Master CUSTOMER_ID中可能有多个条目,您必须确定要排序的可能日期。这通常是每CUSTOMER_ID的第一个或最晚的日期。

您可以使用子查询执行此操作:

select *
from customer_master cm
order by
(
  select max(tm.updatedate)
  from ticket_master tm
  where tm.customer_id = cm.customer_id
) desc;

答案 1 :(得分:0)

试试这个

SELECT distinct(a.*)
FROM customer_master AS a inner join
                      Ticket_master AS b ON a.CUSTOMER_ID = b.CUSTOMERID 
order by b.UPDATEDATE desc