如何根据ID或特定列将查询结果转换为新列?

时间:2017-08-07 13:30:01

标签: sql sql-server-2012

我已经厌倦了一切,但我无法理解。对你的帮助表示感谢。基本上,我有四列:IDfst_nmlst_nmcode我得到了几个重复的行结果,因为有些人有多个代码。

这是我得到的:

+------+----------+----------+--------+
| ID   |  fst_nm  |  lst_nm  |   Code |
+------+----------+----------+--------+
| 987  |  BRADLY  |  MARTIN  |  LB102 |
| 987  |  BRADLY  |  MARTIN  |  LB101 |
| 999  |  DAVID   |   LOZA   |  PG102 |
| 921  |  PATRIC  |  TEST    |  P5102 |
| 900  |  JUSTIN  |  MARTIN  |  P6415 |
| 900  |  JUSTIN  |  MARTIN  |  LB105 |
| 900  |  JUSTIN  |  MARTIN  |  P1003 |
| 880  |  ROBIN   |  JURRY   |  90686 |
| 880  |  ROBIN   |  JURRY   |  90471 |
+------+----------+----------+--------+

这就是我真正想要的:

+------+----------+----------+---------+---------+--------+
| ID   |  fst_nm  |  lst_nm  |  Code   |  Code1  |  Code2 |
+------+----------+----------+---------+---------+--------+
| 987  |  BRADLY  |  MARTIN  |  LB102  |  LB101  |        |
| 999  |  DAVID   |  LOZA    |  PG102  |         |        |
| 921  |  PATRIC  |  TEST    |  P5102  |         |        |
| 900  |  JUSTIN  |  MARTIN  |  P6415  |  LB105  |  P1003 |
| 880  |  ROBIN   |  JURRY   |  90686  |  90471  |        |
+------+----------+----------+---------+---------+--------+

如果一个人有多个代码,我想让每一行都不同,并将代码移动到新列。有没有办法做到这一点是sql或MS访问?请帮帮我!

2 个答案:

答案 0 :(得分:1)

试试这个

Select distinct id,fst_nm,lst_nm,(Select Code From mytable t2 
Where t1.ID = t2.id limit 1) as Code,
(Select Code From mytable t2 Where t1.ID = t2.id limit 1,1) as Code2,
(Select Code From mytable t2 Where t1.ID = t2.id limit 2,1) as Code3
From mytable t1

如果您使用的是MSSQL Server,则会出现更棘手的情况

Select distinct id,fst_nm,lst_nm,
(select top 1 Code From mytable t2 Where t1.ID = t2.Id order by Code),
(SELECT CODE FROM (
        SELECT 
        CODE,ID, ROW_NUMBER() OVER(ORDER BY CODE) AS ROW
        FROM mytable t2 Where t1.ID = t2.id
        ) AS tbl 
        WHERE ROW = 2
) SECONDCODE,
(SELECT CODE FROM (
        SELECT 
        CODE,ID, ROW_NUMBER() OVER(ORDER BY CODE) AS ROW
        FROM mytable t2 Where t1.ID = t2.id
        ) AS tbl 
        WHERE ROW = 3
) THIRDCODE
From mytable t1

答案 1 :(得分:0)

你可以如下所示:

Select * from (
    Select *, RowN = Row_Number() over (partition by id order by Code) from #data ) a
pivot(max(code) for RowN in ([1],[2],[3])) p