2014-01-15 143 views
0

我有2個表,我需要讓他們的一個觀點一樣,如果它是一張桌子2表的交叉表SQL查詢?

表1 DEVICE

+-----+-------+-----------+ 
|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 | 
+-----+-------+-----------+-----+------------+---------+ 

我會很感激任何hel p做到這一點。由於

+0

你必須使用'PIVOT'得到那個結果。你在用什麼數據庫? – user2989408

+0

你正在使用哪些DBMS? Postgres的?甲骨文? –

回答

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

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 
+0

對於SqlFiddle +1 – Mukus