SQL Server连接两个表,按顺序显示一条记录

时间:2016-06-27 10:55:27

标签: sql sql-server join

我遇到SQL Server语句问题。完美的方案是订单和按日期创建的另一个表(作业)然后按降序显示联系信息。目前我可以让脚本显示所有记录,但是如果用户有多个作业,那么它们会被多次显示。

SELECT 
    c.*,
    p.date_created
FROM 
    [db].[dbo].[Contact] AS c
JOIN 
    [db].[dbo].[job] AS p ON p.contact_id = c.contact_id  

UNION

SELECT 
    *,
    0 as date_created 
FROM
    [db].[dbo].[Contact]   
ORDER BY 
    p.date_created DESC

输出

contact_id| date_created         | contact_name         
1         | 8/29/2016 1:07:18 PM | sam  
1         | 8/26/2016 1:04:01 PM | sam 
14        | 8/24/2016 5:07:22 PM | steve

最终输出应该只显示创建的最新日期和一个用户。非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

union select中的列必须与数字和类型匹配,因此在适当的日期转换0

    SELECT 
         c.contact_id
         ,max(p.date_created)
         ,c. contact_name         
    FROM [db].[dbo].[Contact] AS c
    JOIN [db].[dbo].[job] AS p 
        ON p.contact_id = c.contact_id 
    GROUP BY  c.contact_id,c. contact_name 
    union
    select  
         c.contact_id
        ,   convert(datetime, '01/01/1070', 101) as date_created
        , c. contact_name  
    from [db].[dbo].[Contact]   
    ORDER BY p.date_created desc`

无论如何你需要的结果只能通过

获得
    SELECT 
         c.contact_id
         ,max(p.date_created) as max_date_created
         ,c. contact_name         
    FROM [db].[dbo].[Contact] AS c
    LEFT JOIN [db].[dbo].[job] AS p 
        ON p.contact_id = c.contact_id 
    GROUP BY  c.contact_id,c. contact_name 
    ORDER BY  c.contact_id,c. contact_name, max_date_created