如何从第一行和第二行中选择值

时间:2016-07-03 10:55:40

标签: mysql sql

我想从表格中选择数据 假设我们有一张桌子

表Temp

sequence_number | breakdown_number | physical_account | logical_account | debit_amount | credit_amount
----------------+------------------+------------------+-----------------+--------------+---------------
     1          |      1           |       10001      |         10      |            0
     2          |      1           |       0011       |         10      |            0

现在我必须从第一行选择physical_account,从第二行选择逻辑帐户,然后根据细目编号将其插入另一个单行表中。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以在选择LIMIT OFFSET中使用子查询:

INSERT INTO second_table (physical_account, logical_account)
SELECT t.physical_account,
       (SELECT s.logical_account FROM temp s
        ORDER BY s.breakdown_number
        LIMIT 1,1) 
FROM Temp t
ORDER BY t.breakdown_number
LIMIT 1

这将根据breakdown_number订单上的ACSENDING选择第一个和第二个值。

答案 1 :(得分:1)

我将假设sequence_number实际上提供了行的顺序,并且您希望为每个breakdown_number执行此操作。最准确的方法可能是使用变量:

INSERT INTO second_table(physical_account, logical_account)
    SELECT MAX(CASE WHEN seqnum = 1 THEN t.physical_account END),
           MAX(CASE WHEN seqnum = 2 THEN t.logical_account END)
    FROM (SELECT t.*,
                 (@rn := if(@b = t.breakdown_number, @rn + 1,
                            if(@b := t.breakdown_number, 1, 1)
                           )
                 ) as seqnum
          FROM Temp t CROSS JOIN
               (SELECT @rn := 0, @b := -1) params
          ORDER BY t.breakdown_number, t.sequence_number
         ) t
    WHERE rn IN (1, 2)
    GROUP BY t.breakdown_number;

如果sequence_number为每个breakdown_number重新开始,则不需要子查询和变量:

INSERT INTO second_table(physical_account, logical_account)
    SELECT MAX(CASE WHEN t.sequence_number = 1 THEN t.physical_account END),
           MAX(CASE WHEN t.sequence_number = 2 THEN t.logical_account END)
    FROM Temp t
    WHERE t.sequence_number IN (1, 2)
    GROUP BY t.breakdown_number;

最后,在某些情况下,你可以使用黑客:

INSERT INTO second_table(physical_account, logical_account)
    SELECT SUBSTRING_INDEX(GROUP_CONCAT(t.physical_account), ',', 1),
           SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(t.logical_account), ',', 2), ',', -1)
    FROM Temp t
    WHERE t.sequence_number IN (1, 2)
    GROUP BY t.breakdown_number;

关于这种方法的说明:

  • 它将帐户转换为字符串,如果它们在其他时间。
  • group_concat()具有(可配置的)最大长度,因此如果给定breakdown_number有许多记录,则可能会出现运行时错误。

答案 2 :(得分:0)

DECLARE @physical_account varchar(30); /*Data Type as required*/
DECLARE @logical_account varchar(30);
SELECT @physical_account=physical_account FROM Temp WHERE logical_account=NULL AND physical_account='10001'
SELECT @logical_account=logical_account FROM Temp WHERE logical_account='0011' AND physical_account=NULL
INSERT INTO Table_New(physical_account, logical_account) VALUES(@physical_account, @logical_account);