2个表的交叉表SQL查询?

时间:2014-01-15 22:14:22

标签: sql

我有两张桌子,我需要制作一张它们的视图,就好像它是一张单一的桌子一样

表1设备

+-----+-------+-----------+
|DevID|DevName|DevIP      |
+-----+-------+-----------+
|1    |HH1    |192.168.1.1|
+-----+-------+-----------+ 
|2    |HH2    |192.168.1.2|
+-----+-------+-----------+

表2 DEVICECUSTOMDATA

+-----+------------+--------+
|DevID|Name        |Value   |
+-----+------------+--------+
|1    |Model       |CN70    |
+-----+------------+--------+
|1    |BuildVersion|1.2     |
+-----+------------+--------+
|1    |BuildDate   |20140113|
+-----+------------+--------+
|2    |Model       |MC55    |
+-----+------------+--------+
|2    |BuildVersion|1.2     |
+-----+------------+--------+
|2    |BuildDate   |20140110|
+-----+------------+--------+

结果表应为:

+-----+-------+-----------+-----+------------+---------+
|DevID|DevName|DevIP      |Model|BuildVersion|BuildDate|
+-----+-------+-----------+-----+------------+---------+
|1    |HH1    |192.168.1.1|CN70 |1.2         |20140113 |
+-----+-------+-----------+-----+------------+---------+
|2    |HH2    |192.168.1.2|MC55 |1.2         |20140110 |
+-----+-------+-----------+-----+------------+---------+

我很感激任何帮助。感谢

2 个答案:

答案 0 :(得分:1)

SQL SERVER:

请参阅SqlFiddle

SELECT d.DevId, d.DevName, d.DevIp, p.Model, p.BuildVersion, p.BuildDate
FROM DEVICE d
JOIN (
SELECT *
FROM DEVICECUSTOMDATA
PIVOT (MAX(Value) FOR Name IN ([Model], [BuildVersion], [BuildDate])) as Something) p
on d.DevId = p.DevId

答案 1 :(得分:0)

在线工作示例(SQL Server语法):SQL Fiddle

<强>结果:

http://i41.tinypic.com/5xvl0p.jpg

SQL脚本:

    DECLARE @Device TABLE (
    DevID int not null,
    DevName varchar(max) not null,
    DevIP varchar(max) not null
)

insert into @Device values ('1', 'HH1','192.168.1.1')
insert into @Device values ('2', 'HH2','192.168.1.2')

DECLARE @DeviceCustomData TABLE (
    CDevID int not null,
    Name varchar(max) not null,
    Value varchar(max) not null
)

insert into @DeviceCustomData
values ('1','Model','CN70')
insert into @DeviceCustomData
values ('1','BuildVersion','1.2')
insert into @DeviceCustomData
values ('1','BuildDate','20140113')

insert into @DeviceCustomData
values ('2','Model','MC55')
insert into @DeviceCustomData
values ('2','BuildVersion','1.2')
insert into @DeviceCustomData
values ('2','BuildDate','20140110')

SELECT *
FROM
    (SELECT d.DevID, d.DevName, d.DevIP, c.Value, c.Name
    FROM @Device d 
inner join @DeviceCustomData c on d.DevID = c.CDevID) AS SourceTable
PIVOT(
    MIN(Value)
    FOR Name in ([Model],[BuildVersion],[BuildDate])
) as PivotTable

参考:http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx