SQL查询将1列分为3列

时间:2016-08-30 08:23:56

标签: sql sql-server vb.net

我有这张表:

tbl_Masterlist

|Itemcode|Description|Model|
| I1 | Item1 | M1 |
| I2 | Item2 | M2 |
| I3 | Item3 | M3 |

tbl_Conditions

|Itemcode| Condition| Year |
| I1 | 1 | 2014 |
| I2 | 2 | 2014 |
| I3 | 2 | 2014 |
| I1 | 3 | 2015 |
| I2 | 2 | 2015 |
| I3 | 2 | 2015 |
| I1 | 3 | 2016 |
| I2 | 1 | 2016 |
| I3 | 3 | 2016 |

这是预期的输出。

|   Itemcode    |   Description | Model |  2014  |  2015  |  2016 |
|      I1       |      Item1    |   M1  |    1   |     3  |    3  |
|      I2       |      Item2    |   M2  |    2   |     2  |    1  |
|      I3       |      Item3    |   M3  |    2   |     2  |    3  |

我将列年份划分为3列,根据年份选择(3年范围)填充项目条件。

5 个答案:

答案 0 :(得分:2)

您可以将PIVOT用于固定列,如下所示:

SELECT *
FROM
(
    SELECT a.Itemcode, a.[Description], a.Model, b.[Year], b.Condition
    FROM        tbl_Masterlist a 
    INNER JOIN  tbl_Conditions b ON a.Itemcode = b.Itemcode
) src
PIVOT
(
  MAX(Condition) FOR [[Year]] IN([2014], [2015], [2016])
) piv

答案 1 :(得分:1)

select *
from 
(
select  A.Itemcode, A.[Description], A.Mode,
B.Condition, B.[Year] from tbl_Masterlist A join tbl_Conditions B ON A.Itemcode = B.Itemcode
) src
pivot
(
  MAX(CONDITION)
  for YEAR in ([2014], [2015], [2016])
) piv;

答案 2 :(得分:0)

name:    age:
Jack     14
David    16
Paul     15

答案 3 :(得分:0)

SELECT *
FROM
(
    SELECT a.Itemcode, a.[Description], a.Model, b.[Year], b.Condition
    FROM        tbl_Masterlist a 
    INNER JOIN  tbl_Conditions b ON a.Itemcode = b.Itemcode
) src
PIVOT
(
  MAX(Condition) FOR [[Year]] IN([2014], [2015], [2016])
) piv

答案 4 :(得分:0)

您可以使用以下标准SQL透视图:

SELECT  m.Itemcode,m.Description,m.Model
       ,SUM(CASE WHEN c.Years='2014' THEN c.Conditions END) AS '2014'
       ,SUM(CASE WHEN c.Years='2015' THEN c.Conditions END) AS '2015'
       ,SUM(CASE WHEN c.Years='2016' THEN c.Conditions END) AS '2016' 
  FROM tbl_Masterlist AS m 
  LEFT JOIN tbl_Conditions AS c ON m.Itemcode = c.Itemcode
  GROUP BY m.Itemcode,m.Description,m.Model

分享我的测试脚本:

CREATE TABLE tbl_Masterlist(Itemcode varchar(50),Description varchar(50),Model varchar(50));

CREATE TABLE tbl_Conditions(Itemcode varchar(50),Conditions INT,Years varchar(20));

INSERT INTO tbl_Masterlist(Itemcode,Description,Model) 
VALUES('I1','Item1','M1')
,('I2','Item2','M2')
,('I3','Item3','M3')

INSERT INTO tbl_Conditions(Itemcode,Conditions,Years)
VALUES('I1',1,'2014')
,('I2',2,'2014')
,('I3',2,'2014')
,('I1',3,'2015')
,('I2',2,'2015')
,('I3',2,'2015')
,('I1',3,'2016')
,('I2',1,'2016')
,('I3',3,'2016')

希望它可以帮助你。