2014-01-23 54 views
0

我想這個表/查詢在MSAccess中創建以下查詢的最有效方法是什麼?

+--------+-----------------+-----------------+ 
| tag_id | attribute_name | attribute_value | 
+--------+-----------------+-----------------+ 
|  1 | tag_name  | P1001   | 
|  1 | tag_address  | N7:0   | 
|  1 | tag_description | Pump 1 Status | 
|  2 | tag_name  | P1002   | 
|  2 | tag_address  | N7:1   | 
|  2 | tag_description | Pump 2 Status | 
|  3 | tag_name  | P1003   | 
|  3 | tag_address  | N7:2   | 
|  3 | tag_description | Pump 3 Status | 
+--------+-----------------+-----------------+ 

轉換爲該

+----------+-------------+-----------------+ 
| tag_name | tag_address | tag_description | 
+----------+-------------+-----------------+ 
| P1001 | N7:0  | Pump 1 Status | 
| P1002 | N7:1  | Pump 2 Status | 
| P1003 | N7:2  | Pump 3 Status | 
+----------+-------------+-----------------+ 

我知道交叉表查詢存在,但它迫使我挑了價值聚合函數。如果我選擇FirstMax它可行,但它不覺得是最有效的方法。有更好的方法嗎?

回答

0
select tag_name, tag_address, tag_description from 
(
    (
     select tag_id, attribute_value as tag_name 
     from inputtable 
     where attribute_name='tag_name' 
    ) as one 
    left join 
    (
     select tag_id, attribute_value as tag_address 
     from inputtable 
     where attribute_name='tag_address' 
    ) as two 
    on one.tag_id=two.tag_id 
) 
left join 
(
    select tag_id, attribute_value as tag_description 
    from inputtable 
    where attribute_name='tag_description' 
) as three 
on one.tag_id=three.tag_id 
+0

訪問不會喜歡那個查詢。由於在第一對連接的子查詢周圍缺少括號,它會引發語法錯誤。 (訪問是那樣的挑剔。) –

+0

啊...我更像一個SQL Server的傢伙。固定。謝謝你的提示! –

0

正如你在你的問題建議,

TRANSFORM MAX(attribute_value) AS thing 
SELECT tag_id 
FROM your_table 
GROUP BY tag_id 
PIVOT attribute_name IN ('tag_name','tag_address','tag_description') 

會工作。另一種選擇是

SELECT tn.tag_name, ta.tag_address, td.tag_description 
FROM 
    (
     (
      SELECT 
       tag_id, 
       attribute_value AS tag_name 
      FROM your_table 
      WHERE attribute_name = 'tag_name' 
     ) AS tn 
     INNER JOIN 
     (
      SELECT 
       tag_id, 
       attribute_value AS tag_address 
      FROM your_table 
      WHERE attribute_name = 'tag_address' 
     ) AS ta 
      ON ta.tag_id = tn.tag_id 
    ) 
    INNER JOIN 
    (
     SELECT 
      tag_id, 
      attribute_value AS tag_description 
     FROM your_table 
     WHERE attribute_name = 'tag_description' 
    ) AS td 
     ON td.tag_id = tn.tag_id 

但我可能只是去第一個。

相關問題