My table, MARC, has more than 200 columns with WERKS (plant) as the key.
Most of the entries in MARC have values that come from a reference plant. So, usually, all the 200 columns will contain the same values.
I need to find the columns that have different values compared with the reference plant row, in order to find the deviations and show the names of the columns that had different values.
The main question is: how to do the select when it is not known which columns need to be selected.
Example
In the above, ABAS is the reference plant.
I expect only the first row to be returned, because only that row contains any differences compared with the reference row. Differences in that row occur in the following columns:
- WERKS
- PSTAT
- DISMM
- DISPO
The returned row should contain only those four columns.
I do not need any other columns to be able to show on the UI that these 3 columns have different values for that particular WERKS.
I am using SAP HANA.
Best Answer
This answer shows an implementation of the techniques mentioned by Michael Green in comments to the question. It uses SQL Server, but the basic idea is applicable to any SQL-compatible database engine that supports dynamic SQL. Support for
UNPIVOT
andPIVOT
is not required.The broad idea is:
WERKS
using dynamic SQLIt is the use of dynamic SQL that gets around the issue of not knowing which columns to
SELECT
- they are determined dynamically.Sample table and data
Unpivot and find differences
Differences
Dynamic SQL
The constructed SQL statement in
@sql
is:That is the manual
PIVOT
syntax. The final result is obtained by executing the SQL:Results:
This is the minimal set of columns describing the column differences with respect to the reference row, as required.
There is some SQL Server-specific syntax above, but the manual
UNPIVOT
can be achieved in other ways ifAPPLY
orLATERAL
is not supported e.g. with a cross join to a suitable identity matrix table. Generating the dynamic SQL usesFOR XML PATH
as an efficient way to concatenate the strings, but again this can be done in any language.Stack Exchange Data Explorer Demo