SQL - 拉客户端(结果集中每行1个客户端)和这些客户端的最近订单日期

时间:2011-10-19 22:53:34

标签: sql join

下面是一些用于提取客户端列表的SQL。如你所见,我添加了由“ - ADDED”注释的行 - 一个新字段,一个连接和一个订单。我试图在结果集中每行显示一个客户端,但对于每个客户端,我想显示最近的订单。最好的方法是什么?我应该在我的JOIN中放置一个位置还是使用TOP 1?我想有几种方法,但我希望尽可能提高效率。

SELECT 
    CONVERT(NVARCHAR(255),client.identifyingnumber) As [Client ID], 
    CONVERT(VARCHAR,client.name) As [Client Name], 
    client.clientid As [Id],
    CONVERT(CHAR(10),[ecom_order].[order_date],101)  -- ADDED
FROM  
    client 
    JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid 
    JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid 
    -- keep left outer join since some clients won't have any orders, thus no last order
    LEFT OUTER JOIN [ecom_order] ON client.clientid = [ecom_order].clientid -- ADDED
WHERE  
    client.name LIKE '%_%' 
    AND 
    client.name <= (
        SELECT MAX(maxsubquery.ordercolumn) FROM (
            SELECT 
                TOP 10 client.name AS ordercolumn 
            FROM  
                client 
                JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid 
                JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid 
            WHERE  
                client.name LIKE '%_%' 
            ORDER BY client.name
        ) 
        AS maxsubquery)
 ORDER BY 
    client.name,
    [ecom_order].order_date DESC -- ADDED

测试数据结果集示例:

enter image description here

1 个答案:

答案 0 :(得分:2)

试试这个

   SELECT 
        CONVERT(NVARCHAR(255),client.identifyingnumber) As [Client ID], 
        CONVERT(VARCHAR,client.name) As [Client Name], 
        client.clientid As [Id],
      -- Change to get latest
        CONVERT(CHAR(10),Max([ecom_order].[order_date]),101)       
     FROM  client 
        JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid 
        JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid 
        -- keep left outer join since some clients won't have any orders, 
     -- thus no last order
        LEFT OUTER JOIN [ecom_order] ON client.clientid = [ecom_order].clientid 
    WHERE  
        client.name LIKE '%_%' 
        AND 
        client.name <= (
            SELECT MAX(maxsubquery.ordercolumn) FROM (
                SELECT 
                    TOP 10 client.name AS ordercolumn 
                FROM  
                    client 
                    JOIN clientstatus ON client.clientstatusid = clientstatus.clientstatusid 
                    JOIN clienttype ON clienttype.clienttypeid = client.clienttypeid 
                WHERE  
                    client.name LIKE '%_%' 
                ORDER BY client.name
            ) 
            AS maxsubquery)
     GROUP BY client.identifyingnumber,client.name,client.client_id
     ORDER BY 
        client.name