访问sql查询水平到垂直

时间:2015-11-09 18:38:33

标签: sql ms-access-2010

我有一张映射表

EK_ID   CS      EK_ID-CS    
1001    1071    1001_1071   
1001    1015    1001_1015
1004    1061    1004_1061
1004    1007    1004_1007
1004    1006    1004_1006
1004    1005    1004_1005
1005    1011    1005_1011
1005    1010    1005_1010
1006    1013    1006_1013
1006    1012    1006_1012

和表B,其具有公共字段EK_ID。

EK_ID   S1      S2        S3    S4
1001    0.94    0.03    0.01    
1004    0.96    8.12    38.10   0.06
1005    1       2.30        
1006    1       2.47        

内部连接直到字段S1给出结果

 EK_ID  CS     EK_ID-CS S1

1001    1071    1001_1071   0.94
1001    1015    1001_1015   0.94
1004    1061    1004_1061   0.96
1004    1007    1004_1007   0.96
1004    1006    1004_1006   0.96
1004    1005    1004_1005   0.96
1005    1011    1005_1011   1
1005    1010    1005_1010   1
1006    1013    1006_1013   1
1006    1012    1006_1012   1

我试图将表B中的列S2,S3,S4值写为一列S2,垂直如下

 EK_ID  CS        EK_ID-CS  S1       S2
1001    1071    1001_1071   0.94    0.03
1001    1015    1001_1015   0.94    0.01
1004    1061    1004_1061   0.96    
1004    1007    1004_1007   0.96    8.12
1004    1006    1004_1006   0.96    38.10
1004    1005    1004_1005   0.96    0.06
1005    1011    1005_1011   1      2.30
1005    1010    1005_1010   1   
1006    1013    1006_1013   1      2.47
1006    1012    1006_1012   1   

如何在访问sql查询中表示?

1 个答案:

答案 0 :(得分:0)

考虑使用计算行数的派生表,并有条件地使用RowCount来检索S列。这应该符合大多数SQL方言,只需更改Access' IIF()到ANSI-SQL CASE/WHEN

SELECT EK_ID, CS, [EK_ID-CS], S1,
       IIF(RowCount = 2, dTS2, 
           IIF(RowCount = 3, dTS3, 
               IIF(RowCount = 4, dTS4, NULL))) As S2
FROM 
    (SELECT TableA.EK_ID, TableA.CS, TableA.[EK_ID-CS], TableB.S1, 
           TableB.S2 As dTS2, TableB.S3 As dTS3, TableB.S4 As dTS4,
           (SELECT Count(*) + 1 FROM TableA t2 
            WHERE t2.EK_ID = TableA.EK_ID AND t2.CS >= TableA.CS) As RowCount
    FROM TableA INNER JOIN TableB ON TableA.EK_ID = TableB.EK_ID
    ORDER BY TableA.EK_ID, TableA.CS DESC
    ) As DerivedTable

<强>输出

EK_ID   CS      EK_ID-CS    S1      S2
1001    1071    1001_1071   0.94    0.03
1001    1015    1001_1015   0.94    0.01
1004    1061    1004_1061   0.96    8.12
1004    1007    1004_1007   0.96    38.1
1004    1006    1004_1006   0.96    0.06
1004    1005    1004_1005   0.96    
1005    1011    1005_1011   1       2.3
1005    1010    1005_1010   1   
1006    1013    1006_1013   1       2.47
1006    1012    1006_1012   1