简体   繁体   English

如何根据 SQL Server 中的另一列将一列值转换为两个不同的列值?

[英]How to convert one column values to two different column values based on other column in SQL Server?

I have a table A with columns B and C .我有一个包含B列和C列的表A

  • Column B contains digit 2's and 4's. B列包含数字 2 和 4。
  • Column C contains respective numeric values for column B C列包含B列的相应数值

For example:例如:

table rows >>> (2,25),(4,6),(2,10),(4,54),(4,20),(2,30)

My requirement is, I need the result set with column names 2 and 4 and the respective values as rows.我的要求是,我需要列名称为 2 和 4 的结果集以及作为行的相应值。

I'd like the result set of rows to be:我希望行的结果集是:

>>> (25,6),(10,54),(30,20)

You need to have a way to order the records in an unique way, so you are sure which row with value 2 to which tow with value 4 to match.你需要有一种方法以独特的方式订购的记录,所以你一定行其值为2到拖值为4相匹配。

In the example below I have added identity column to initially have a way to distinguish the rows and then use simply ROW_NUMBER to define how the rows are going to be combined.在下面的示例中,我添加了标识列以最初有一种方法来区ROW_NUMBER ,然后简单地使用ROW_NUMBER来定义行将如何组合。

Once, you have such column, the rest is simple JOIN :一旦,你有这样的列,剩下的就是简单的JOIN

DECLARE @DataSource TABLE
(   
    [row_id] INT IDENTITY(1,1)
   ,[value_one] INT
   ,[value_two] INT
);

INSERT INTO @DataSource ([value_one], [value_two])
VALUES (2,25)
      ,(4,6)
      ,(2,10)
      ,(4,54)
      ,(4,20)
      ,(2,30);

SELECT *
FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY [row_id]) AS [row_id]
          ,[value_one], [value_two]
    FROM @DataSource
    WHERE [value_one] = 2
) DS1
INNER JOIN
(
    SELECT ROW_NUMBER() OVER (ORDER BY [row_id]) AS [row_id]
          ,[value_one], [value_two]
    FROM @DataSource
    WHERE [value_one] = 4
) DS2
    ON DS1.[row_id] = DS2.[row_id];

If there can be any ordering of the rows , say if you have an additional column ID on which the rows can be ordered then the following may work - Use the [Lead] function (read more here ) to get the next value in the current row (assuming the first row starts with col B as 2, next row with col B as 4 and so on), then we can just get the alternate rows from the dataset.如果可以对行进行任何排序,例如如果您有一个额外的列ID可以对行进行排序,那么以下可能有效 - 使用[Lead]函数( 在此处阅读更多信息)获取当前的下一个值行(假设第一行以 col B 为 2,下一行以 col B 为 4,依此类推),然后我们可以从数据集中获取备用行。

DECLARE @A TABLE (ID INT IDENTITY(1,1), B INT, C INT)

INSERT INTO @A(B, C) VALUES (2,25)
INSERT INTO @A(B, C) VALUES (4,6)
INSERT INTO @A(B, C) VALUES (2,10)
INSERT INTO @A(B, C) VALUES (4,54)
INSERT INTO @A(B, C) VALUES (2,30)
INSERT INTO @A(B, C) VALUES (4,20)

;WITH [Data] AS (
SELECT *, C AS [2], LEAD(C) OVER (ORDER BY ID) AS [4]
FROM @A
)
SELECT d.[2], d.[4]
FROM Data d
WHERE d.Id %2 != 0

Outputs:输出:

2  |4
-- |--
25 |6
10 |54
30 |20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM