8

私はこのトピックについて少し調査を行ってきましたが、実行可能な解決策、または実装するのに十分に説明されている解決策を見つけることができないようです。

Access でクロス集計クエリを作成したことがある場合は、Access では既定で列がアルファベット順に並べ替えられることをご存知でしょう。この順序を変更するには、 [プロパティ] ダイアログに移動し、希望する順序で列見出しを入力します。これは本当に苦痛ですが、ある回答者が別のサイトで述べたように、「それは一度だけの苦痛です!」

まあ...列が動的である場合、これは当てはまりません。私の場合、テーブルに 2 番目の列があり、そのフィールドを並べ替えに使用したい列見出しが含まれています。ソート列の詳細を説明列の前に追加できると思いますが(他の場所で提案されています)、これが問題を解決する最もエレガントな手段だとは思いません。並べ替え情報はシステム データであり、クロス集計のエンド ユーザーには役に立たないため、これは特に問題です。

この問題の解決策を知っている人はいますか? もしそうなら、クロス集計クエリの動的列を並べ替える手順を詳しく説明していただけますか?

この問題は、一般的に使用されている Access のすべてのバージョン (Access 2003 以降) で持続すると思いますが、念のため、Access 2010 を使用しています。


アップデート

問題を表現するのに役立つ非常に単純化されたサンプル データを次に示します。私のライブ シナリオには他にもいくつかの複雑な問題がありますが、このデータ セットは確かに的を射ています。

表 #1 これが見出しの由来です。はKey列順序のソートで、Descriptionsはクロス集計で出力される見出しです。

+---------+---------------------------------------+
| Key     | Descriptions                          |
+---------+---------------------------------------+
| Kfsg2E  | Hey, this is accounting code X!       |
+---------+---------------------------------------+
| abR3    | This is yet another accounting code!  |
+---------+---------------------------------------+
| Gruu!   | Yet another accounting code           |
+---------+---------------------------------------+

テーブル #2これはデータのストアで P_Key + F_Keyあり、2 つがテーブルの主キーです。

+---------+---------+-------+
| P_Key   | F_Key   | Value |
+---------+---------+-------+
| 1001    |Kfsg2E   | 1.0   |
+---------+---------+-------+
| 1001    |abR3     | 1.1   |
+---------+---------+-------+
| 1001    |Gruu!    | 1.2   |
+---------+---------+-------+
| 1002    |Kfsg2E   | 2.0   |
+---------+---------+-------+
| 1002    |abR3     | 2.1   |
+---------+---------+-------+
| 1002    |Gruu!    | 2.2   |
+---------+---------+-------+
| 2001    |Kfsg2E   | 3.0   |
+---------+---------+-------+
| 2001    |abR3     | 3.1   |
+---------+---------+-------+
| 2001    |Gruu!    | 3.2   |
+---------+---------+-------+

クロス集計結果 これらは、ユーザーが更新できるように Excel にエクスポートされます。

+---------+---------------------------------+--------------------------------------+-----------------------------+
| P_Key   | Hey, this is accounting code X! | This is yet another accounting code! | Yet another accounting code |
+---------+---------------------------------+--------------------------------------+-----------------------------+
| 1001    | 1.0                             | 1.1                                  | 1.2                         |
+---------+---------------------------------+--------------------------------------+-----------------------------+
| 1001    | 2.0                             | 2.1                                  | 2.2                         |
+---------+---------------------------------+--------------------------------------+-----------------------------+
| 1001    | 3.0                             | 3.1                                  | 3.2                         |
+---------+---------------------------------+--------------------------------------+-----------------------------+

これは、Access がこれらの列を並べ替える方法です。ただし、次の表のようにする必要があります。これはTable #1、 ではなくのキーでソートされていますDescription

+---------+--------------------------------------+-----------------------------+---------------------------------+
| P_Key   | This is yet another accounting code! | Yet another accounting code | Hey, this is accounting code X! |
+---------+--------------------------------------+-----------------------------+---------------------------------+
| 1001    | 1.1                                  | 1.2                         | 1.0                             |
+---------+--------------------------------------+-----------------------------+---------------------------------+
| 1001    | 2.1                                  | 2.2                         | 2.0                             |
+---------+--------------------------------------+-----------------------------+---------------------------------+
| 1001    | 3.1                                  | 3.2                         | 3.0                             |
+---------+--------------------------------------+-----------------------------+---------------------------------+
4

3 に答える 3

11

同じシナリオに何度も遭遇したため、PIVOT 句の末尾に In リストを追加する繰り返し可能な方法を用意しました。そうすることで、クロス集計クエリの列がピボットフィールドの In リストの要素の順序で並べ替えられますこの構造のドキュメントは、MSDN から入手できます。解決策は、フォーム上のコマンド ボタンまたは別のイベントによってトリガーされる必要がある手順です。サブの下のスクリーン ショットを参照してください。

Public Sub SortPivotColumns(querynameSource As String, queryname As String, SortName As String, SortColumnNameField As String, SortIndexName As String, NonPivotFieldCount As Integer, ParamArray ParamArr() As Variant)

' This sub goes through several steps to effectively adds an In list that sorts the 'Columns' of a crosstab query in MS Access
' 13 November 2012
' E Easterly
'
' This technique uses several components.
' 1) The original unmodified cross tab query (querynameSource)
' 2) The resulting, columns-have-been-sorted query (query)
' 3) An index table which has two columns, a numeric index used for sorting and the column name
' 4) A table or query that can be joined on the column names of the cross tab query to update the index table
'    The name of the table or query would be 'SortName'
'    The field in 'SortName' that the crosstab query columns are joined against is the 'SortColumnNameField'
'    The field in 'SortName' that has the desired order is the SortIndexName
' 5) A number which specifies the count of non-pivot/row heading columns (NonPivotFieldCount)
' 6) An optional array that contains any parameters needed for the query
'
'
'   USE:
'
'   SortPivotColumns "qryCrosstab_Initial", _
'                 "qryCrosstab_Sorted", _
'                 "tblKeyDescriptions", _
'                 "Descriptions", _
'                 "NumericIndexForSorting", _
'                  1
'
'
'
'
Dim rs As DAO.Recordset
Dim db As Database
Dim fld As DAO.Field
Dim sql As String
Dim ColumnHeading As Variant
Dim qdf As QueryDef
Dim qdfSRC As QueryDef
Dim UpdateIndexSQL As Variant

DoCmd.SetWarnings False 'Turn off warnings

Set db = CurrentDb

Set qdfSRC = db.QueryDefs(querynameSource)
Set qdf = db.QueryDefs(queryname)
qdf.sql = qdfSRC.sql

If Not (IsEmpty(ParamArr)) Then
    Dim i As Integer
    For i = 0 To UBound(ParamArr)
        qdf.Parameters(i) = ParamArr(i)
    Next
End If


' First, get the list of fields from the query

Set rs = qdf.OpenRecordset

' Then, create a temporary indexing table
If Not IsNull(DLookup("Name", "MSysObjects", "Name='ttblSortCrosstabColumns' And Type In (1,4,6)")) Then
    db.Execute "DROP TABLE ttblSortCrosstabColumns"
End If

db.Execute "CREATE TABLE ttblSortCrosstabColumns (FieldIndex INTEGER , ColumnName TEXT(250))"

' And populate it with the current index and column names from queryname
  For Each fld In rs.Fields
    If fld.OrdinalPosition > (NonPivotFieldCount - 1) Then
        DoCmd.RunSQL "Insert into ttblSortCrosstabColumns VALUES(" & fld.OrdinalPosition & ", """ & fld.Name & """)"
    End If
  Next fld
  Set fld = Nothing
  rs.Close
  Set rs = Nothing


' Now, the temporary table is joined with the sort table/query and the indexes are updated
UpdateIndexSQL = ("  UPDATE ttblSortCrosstabColumns " & _
                  "  INNER JOIN " & SortName & " ON ttblSortCrosstabColumns.ColumnName=" & SortName & "." & SortColumnNameField & _
                  "  Set ttblSortCrosstabColumns.FieldIndex = [" & SortIndexName & "]")
DoCmd.RunSQL (UpdateIndexSQL)


' Then, the column headings are added to a string to prepare the In list
sql = "SELECT ttblSortCrosstabColumns.ColumnName FROM ttblSortCrosstabColumns ORDER BY ttblSortCrosstabColumns.FieldIndex"
Set rs = db.OpenRecordset(sql)
    rs.MoveFirst
    ColumnHeading = "'" & rs.Fields(0).Value & "'"
    rs.MoveNext

    Do While Not rs.EOF
    ColumnHeading = ColumnHeading & ", '" & rs.Fields(0).Value & "'"
    rs.MoveNext
    Loop

rs.Close
Set rs = Nothing
' db.Execute "DROP TABLE ttblSortCrosstabColumns"

Dim cs As Variant

' Set qdf = db.QueryDefs(queryname)   ' may not need this

' The query is updated with the In list
cs = Left$(qdf.sql, Len(qdf.sql) - 3) & " In(" & ColumnHeading & ");"

qdf.sql = cs

' Take a look at the resulting query sql by uncommenting the below section
' Debug.Print cs


DoCmd.SetWarnings True  'Turn warnings back on

End Sub

以下のスクリーン ショットで、tblKeyDescriptions と tblPFValues に注意してください。これらは質問からのものです。qryCrosstab_Initial は、上記の質問で提供されたクエリに類似しています。フォームは、プロシージャを実行し、前後のクエリを開くために使用されます。

スクリーン ショットのクロス集計の並べ替え

整数フィールド (NumericIndexForSorting) が tblKeyDescriptions に追加されました。これは、サブルーチンが列名をソートするために数値インデックスを必要とするためです。

数値インデックス付きのキー説明テーブル

ここで、最初のクエリと並べ替えられたクエリの SQL ビューで強調表示されている In リストを調べます。

PIVOT 句に表示される SQL の相違点

クロス集計クエリで列を並べ替えるために必要なことはこれだけです。サブの目的は、In リストを動的に生成することです。

注: クエリを実行するたびにサブルーチンを実行する必要があるため、コマンド ボタンの On Click イベントなどのイベントを使用してシーケンスを結び付けると便利です。

于 2012-12-24T19:48:33.773 に答える
1

Access と Excel を使用する完全ではないソリューションを次に示します。

  1. クロス集計を作成するときは、列に Table1.Key を使用します。
  2. Excel ファイルの新しいタブ (「ルックアップ」と呼びますか?) で、Table#1 を作成します。
  3. Excel ファイルのメイン タブの最初の行 (つまり、データセットが貼り付けられている場所) で、一連の Vlookup() 式を作成して行 #2 を調べ、ルックアップ テーブルから正しい説明を取得します。
  4. データセットを行 #2 に貼り付けます。結果は下の表になります。最初の行は、実際には正しい列の説明を取得する一連の Vlookup です。
  5. 行 #2 を無視するか削除するようユーザーに依頼します。

スクリプトがどれほど複雑かはわかりませんが、このデータがオートメーションによって Excel ファイルに貼り付けられている場合は、行 #2 を非表示にして手順 6 をスキップできます。

P_キー これはまた別の会計コードです。 さらに別の会計コード ねえ、これは会計コード X です !
ここに貼り付け abR3 グル! Kfsg2E
1001 1.1 1.2 1.0
1001 2.1 2.2 2.0
1001 3.1 3.2 3.0
于 2012-12-13T17:22:36.880 に答える