如何追加与其他表多列数据匹配的表

时间:2016-12-12 05:06:51

标签: mysql sql-server

我有两张桌子。一个在表A中有50个记录,另一个在表B中有100个记录。 两个表都有客户ID和日期。 两个表都有重复,但50表中的唯一客户数量较少。

现在我希望在表A中将客户的日期放在客户面前。客户可以在表B中出现超过2次。

因此显示的时间,在客户面前附加日期的列数。

Id Date 1 1/01/2016 2 2/01/2016 2 3/01/2016 3 1/01/2016 4 4/01/2016 5 5/01/2016 6 1/01/2016 7 3/01/2016 8 4/01/2016 9 1/01/2016 1 6/01/2016 10 1/01/2016

例如。这是表A

和表B是

Id Date 1 1/01/2016 2 2/01/2016 2 3/01/2016 3 1/01/2016 4 4/01/2016 5 5/01/2016 6 1/01/2016 7 3/01/2016 8 4/01/2016 9 1/01/2016 1 6/01/2016 10 1/01/2016 1 15/01/2016 2 16/01/2016 2 17/01/2016 3 18/01/2016 4 19/01/2016 5 20/01/2016 6 21/01/2016 7 16/01/2016 8 20/01/2016 9 21/01/2016 1 16/01/2016 10 18/01/2016 1 19/01/2016 2 2/02/2016 2 30/01/2016 3 16/01/2016 4 31/01/2016 5 21/01/2016 6 18/01/2016 7 19/01/2016 8 16/01/2016 9 2/02/2016 1 18/01/2016 10 19/01/2016

我希望在

下提供输出
  

Id Date Date1 Date2 1 1/01/2016 15/01/2016 19/01/2016 2 2/01/2016 16/01/2016 2/02/2016 2 3/01/2016 17/01/2016 30/01/2016 3 1/01/2016 18/01/2016 16/01/2016 4 4/01/2016 19/01/2016 31/01/2016 5 5/01/2016 20/01/2016 21/01/2016 6 1/01/2016 21/01/2016 18/01/2016 7 3/01/2016 16/01/2016 19/01/2016 8 4/01/2016 20/01/2016 16/01/2016 9 1/01/2016 21/01/2016 2/02/2016 1 6/01/2016 16/01/2016 18/01/2016 10 1/01/2016 18/01/2016 19/01/2016

任何帮助都非常明显。感谢

2 个答案:

答案 0 :(得分:0)

这应该解释如何使用连接。一旦你了解了,你就可以自己编写SQL。

http://www.w3schools.com/sql/sql_join.asp

尝试理解LEFT和内部联接

答案 1 :(得分:0)

试试这个(不容易)

func combineDateAndTime(date: Date, time: Date) -> Date {

    let calendar = NSCalendar.current

    let dateComponents = calendar.dateComponents([.year, .month, .day], from: date)
    let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: time)

    var components = DateComponents()
    components.year = dateComponents.year
    components.month = dateComponents.month
    components.day = dateComponents.day
    components.hour = timeComponents.hour
    components.minute = timeComponents.minute
    components.second = timeComponents.second

    return calendar.date(from: components)!
}