簡體   English   中英

Access中的多個自我聯接或聯合

[英]multiple self joins or unions in Access

我有這個虛擬的臨時表,看起來像這樣

      ID     Sum    Indicator       Month    Year
       1     10     Ind1             3       2016
       1     20     Ind2             3       2016
       2     15     Ind1             3       2016
       2     19     Ind3             3       2016
       .     .      .                .       .
       .     .      .                .       . 
       50    5      Ind1             3       2016
       50    5      Ind2             3       2016
       50    5      Ind3             3       2016

我想要得到的結果如下:

 ID    Ind1     Ind2    Ind3    Month    Year
 1     10       20      null    3        2016
 2     15       null    19      3        2016
 50    5        5       5       3        2016

我試過的

   select  a.ID,b.sum as Ind1,c.sum as Ind2,d.sum as Ind3  
   from (
          ( 
          dummytable a 
          left join dummytable b 
          on a.ID=b.ID
          )
        left join dummytable c 
        on a.ID=c.ID
        ) 
   left join dummytable d 
   on a.ID=d.ID 
   where b.Indicator=Ind1  and c.Indicator=Ind2 and d.Indicator=Ind3

該位捕獲所有具有Ind1,2,3值的ID,因此在我的示例中僅顯示所需結果的最后一行。 我知道,由於Access不支持完全聯接,因此應該使用聯合來捕獲其余的組合。 但是,我繼續用union進行操作,我得到一條錯誤消息(不支持join表達式)或重復相同結果的值。 有什么建議么?

如前所述,請考慮MS Access的唯一數據透視查詢crosstab ,它是Access UI的“創建功能區查詢”選項卡中列出的對象。 在設計視圖中,您將選擇兩種GROUP BY類型的列(最后一個Values是聚合類型的Values除外)

  1. 行標題字段(例如,ID,​​月,年)-可以是多個表列
  2. 列標題字段(例如,指示符) -只能其中列結果在單獨的列
  3. 值字段(例如Sum)-使用聚合函數只能是列-Sum(),Max(),Avg()等。

將創建結果SQL(請注意,已嵌入聚合查詢):

TRANSFORM Sum(dummytable.Sum) AS SumOfSum
SELECT dummytable.ID, dummytable.Month, dummytable.Year
FROM dummytable
GROUP BY dummytable.ID, dummytable.Month, dummytable.Year
PIVOT dummytable.Indicator;

結果

ID  Month   Year    Ind1    Ind2    Ind3
1   3       2016    10      20  
2   3       2016    15              19
50  3       2016    5       5       5

若要使通用的RDMS數據透視查詢在Access之外工作,只需使用條件聚合。 請注意,在其他SQL方言中, IIF()函數必須替換為CASE/WHENIF/THEN

SELECT dummytable.ID, dummytable.Month, dummytable.Year,
          SUM(IIF(dummytable.Indicator = 'Ind1', [Sum], NULL)) As Ind1,
          SUM(IIF(dummytable.Indicator = 'Ind2', [Sum], NULL)) As Ind2,
          SUM(IIF(dummytable.Indicator = 'Ind3', [Sum], NULL)) As Ind3

FROM dummytable
GROUP BY dummytable.ID, dummytable.Month, dummytable.Year;

若要創建多值字段交叉表查詢,必須為要計算的每個值創建一個單獨的交叉表查詢。 然后,您可以使用選擇查詢將這些交叉表查詢聯接起來,以顯示所需的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM