将多行合并为一行

时间:2017-06-25 17:40:22

标签: mysql

我已经查看了几个类似的问题,但找不到我想要做的确切内容。

我想将多行合并为一行,但有条件地为每个结果行选择值。

测试表:

enter image description here

AnotherTest表:

enter image description here

我想通过SomeId对Test表进行分组,例如分组全部50s,51s,52s等。 生成的行应始终使用SomeId = 1的行中的值,如果匹配的AnotherTable,则在TestTable.YetAnotherId = AnotherTest.YetAnotherId时应该具有OneMoreId。 此外,它应该选择具有以下逻辑的AnotherValue:如果有多个SomeId = 2的行,则AnotherValue应该等于1234 - 除非所有具有SomeId = 2的行具有相同的值。

这是预期的输出

enter image description here

create table Test (SomeId int, AnotherId int, YetAnotherId int not null primary key, Value int,AnotherValue int)
insert into Test (SomeId, AnotherId, YetAnotherId, Value,AnotherValue) values (1,50,22,200,null), (2,50,23,50,55), (2,50,24,75,55)
insert into Test (SomeId, AnotherId, YetAnotherId, Value,AnotherValue) values (1,51,25,300,null), (2,51,26,50,66), (2,51,27,75,67)
insert into Test (SomeId, AnotherId, YetAnotherId, Value,AnotherValue) values (1,52,30,500,null), (2,52,31,50,77)



create table AnotherTest (YetAnotherId int, OneMoreId int)
  insert into AnotherTest (YetAnotherId, OneMoreId) values (25, 777), (31, 555)

2 个答案:

答案 0 :(得分:1)

我想你是在追求这样的事情......

SELECT a.value
     , MAX(y.onemoreid) onemoreid  
  FROM test a 
  LEFT 
  JOIN test b 
    ON b.anotherid = a.anotherid 
  LEFT 
  JOIN anothertest y 
    ON y.yetanotherid = b.yetanotherid 
 WHERE a.someid = 1 
 GROUP 
    BY a.value;

答案 1 :(得分:-1)

不确定我是否正确理解了您的问题,但请您检查一下加入表是否是您的解决方案?

这将显示测试表中的每一行,如果在另一个表中找到,还会显示另一个id。

  SELECT t.value,a.OneMoreId FROM test AS t 
  LEFT JOIN anothertest AS a ON a.YetAnotherId = t.YetAnotherId

如果您只想查看是否在两个表中都找到了。使用内连接

  SELECT t.value,a.OneMoreId FROM test AS t 
  INNER JOIN anothertest AS a ON a.YetAnotherId = t.YetAnotherId

注意:您可以删除" INNER"关键字,因为它是默认的加入。 希望它有所帮助

更新:这可能会按预期工作

SELECT mainTest.Value,(  
    SELECT a.OneMoreId FROM anothertest AS a 
    INNER JOIN test AS t ON t.YetAnotherId = a.YetAnotherId
    WHERE t.AnotherId= maintest.AnotherId)  AS OneMoreId
 FROM test AS mainTest
 GROUP BY AnotherId
相关问题