SQL两条记录,应该是一条

时间:2015-05-14 18:12:00

标签: sql join

我一直在寻找这个问题的答案,我仍然在努力。

.AsParallel()
.Select(o => Parse(o))
.MagicFlatten();

我希望具有相同位置,收银台,日期和时间的记录仅出现一次,两个适用的参考线位于一个框中...例如

Location    Cashier TXN Date    Product Date    Time    Ref
Toronto     Z       15-01-04    15-01-04        090501  Transaction was a very
Toronto     Z       15-01-04    15-01-04        090501  intresting one
NewYork     X       15-01-04    15-01-04        123035  Transaction completed
London      Z       15-02-04    15-01-04        100612  This transaction had complications
London      Z       15-02-04    15-01-04        100612  in it. We need to follow up
Rochest     Y       15-01-04    15-01-04        153045  This transaction was a fun one to
Rochest     Y       15-01-04    15-01-04        153045  process
Vanc        L       15-01-04    15-01-04        174535  Something intresting

我知道这是相当基本的,但在我的SQL学习之旅中,任何帮助都会受到赞赏

由于

3 个答案:

答案 0 :(得分:0)

如果你使用的是oracle,你可以使用listagg

SELECT location, cashier, txn_date, product_date, time       LISTAGG(ref, '; ') WITHIN GROUP (ORDER BY ref) as "ref_list"
  FROM mytable;

答案 1 :(得分:0)

Sample SQL Fiddle

您可以使用STUFF和Group BY进行组合。假设您使用的是SQL Server。

Select location,Cashier,[Time],
  stuff((SELECT distinct ', ' + cast(ref as varchar(500))
           FROM t t2
           where t2.location = t1.location
           FOR XML PATH('')),1,1,'') 
Grom t t1
Group By location, Cashier,[Time]

答案 2 :(得分:-1)

如果您在示例中列出了数据,请使用此查询:

这个查询已经为MySQL完成了。

  select distinct Location,
                  Cashier,
                  time,
                  concat((select ref
                           from test
                          where Location = 'Toronto' limit 1),
                         (select ref
                            from test
                           where Location = 'Toronto' limit 1 offset 1))
    from test;

输出应该是这样的:

Toronto  | Z       |  90501 | Transaction was a veryintresting one 

有三个值

select distinct t.Location,
                  t.Cashier,
                  t.time,
                  concat((select ref
                           from test
                          where Location = 'Toronto' limit 1),
                         (select ref
                            from test
                           where Location = 'Toronto' limit 1 offset 1),
                           (select ref
                            from test
                           where Location = 'Toronto' limit 1 offset 2))
   from test t where t.Location = 'Toronto';