将2个结果记录转换为1

时间:2016-09-26 17:24:38

标签: sql tsql

我需要占用2行表(它总是2行)并将它们合并为1行,以便表中的这些字段:

  

烘烤时间,直径,尺寸,高度

最终会像

一样
  

BakeTime1,BakeTime2,Diameter1,Diameter2,Size1,Size2,Height1,Height2

在最终结果记录中。有一个独特的ID'表中的字段,对于我想要一起输出的2条记录是唯一的。

4 个答案:

答案 0 :(得分:1)

您应该能够使用内部联接从两个记录生成单个行。根据关于标识列(CakeNo)的注释中的语句,下面的内容应该有效。

echo $email_error

免责声明:我不完全确定我理解你对CakeNo的使用,可能需要LEFT(t1.CakeNo,1)='1'代替RIGHT(t1.CakeNo,1)='A'。< / p>

答案 1 :(得分:1)

如果身份证明有所不同 - 您的问题不明确

SELECT t1.*, t2.*   // yes you need to alias actual column names
FROM YourTable t1
JOIN YourTable t2 
      ON t1.UniqueId = 1   // id1
     AND t2.UniqueId = 2   // id2

如果ID相同且CakeNo不同 大量借用马特(+1)

;WITH cte AS (
    SELECT *
         , ROW_NUMBER() OVER (PARTITION BY uniqueID ORDER BY CakeNo) as RowNum
    FROM
       TableName
  --where uniqueID = @ID -- in you only need one do it here  
)

SELECT
     c1.BakeTime as BakeTime1
    ,c2.BakeTime as BakeTime2
    ,c1.Diameter as Diameter1
    ,c2.Diameter as Diameter2
    ,c1.Size as Size1
    ,c2.Size as Size2
    ,c1.Height as Height1
    ,c2.Height as Height2
FROM
    cte c1
    left JOIN cte c2  -- in case only one row  
     ON c2.RowNum = 2
    AND c1.RowNum = 1
如果两个CakeNo相同,这是有效的 如果有两个以上具有相同ID的行,则只需获得前2个

答案 2 :(得分:1)

;WITH cte AS (
    SELECT
       *
       ,LEFT(CakeNo,LEN(CakeNo) - 1) as CorrelationId
       ,ROW_NUMBER() OVER (PARTITION BY LEFT(CakeNo,LEN(CakeNo) - 1) ORDER BY CakeNo) as RowNum
    FROM
       TableName
)

SELECT
    c1.BakeTime as BakeTime1
    ,c2.BakeTime as BakeTime2
    ,c1.Diameter as Diameter1
    ,c2.Diameter as Diameter2
    ,c1.Size as Size1
    ,c2.Size as Size2
    ,c1.Height as Height1
    ,c2.Height as Height2
FROM
    cte c1
    INNER JOIN cte c2
    ON c1.CorrelationId = c2.CorrelationId
    AND c2.RowNum = 2
WHERE
    c1.RowNum = 1

根据您的评论,您可以从获取CakeNo的第一个字符派生相关ID。因为我认为你将拥有超过9条记录,所以我想到这就好像你从最后删除A / B你可以到达你的CorrelationId。我已经更新了我的答案以反映这一点。

答案 3 :(得分:0)

因为你总是只有两行尝试这样的事情

SELECT Concat(Min(baketime), ',', Max(baketime)), 
       Concat(Min(diameter), ',', Max(diameter)), 
       Concat(Min(size), ',', Max(size)), 
       Concat(Min(height), ',', Max(height)) 
FROM   yourtable 

如果您使用的内容少于SQL Server 2012,请将CONCAT替换为+运算符以连接字符串

更新:看起来你想要这个

SELECT Min(baketime), 
       Max(baketime), 
       Min(diameter), 
       Max(diameter), 
       Min(size), 
       Max(size), 
       Min(height), 
       Max(height) 
FROM   yourtable