String subQueryAlias = "t" + System.currentTimeMillis();
String normalizedSubQueryAlias = "n" + System.currentTimeMillis();
String dimGeoAlias = "g" + System.currentTimeMillis();
Hierarchy hierarchy = getSelectedHierarchy();
Hierarchy.Level level = getSelectedLevel();
String baseLevelName = getMetaData().getLevelName( hierarchy.getName() );
Hierarchy.Level baseLevel = hierarchy.getLevel( baseLevelName );
if(hierarchy.getType().equalsIgnoreCase("custom")) {
System.out.println("\nCUSTOM HIERARCHY...\n");
String aggregationColumnName = level.getColumnId();
aggragateQuery = "SELECT * " ;
aggragateQuery += " \nFROM ( " + query + ") " + subQueryAlias;
aggragateQuery += " \nWHERE " + subQueryAlias + "." + level.getColumnId();
aggragateQuery += " = '" + filterValue + "'";
} else {
System.out.println("\nDEFAULT HIERARCHY...\n");
String aggregationColumnName = level.getColumnId();
aggragateQuery = "SELECT * ";
String[] kpiColumnNames = (String[])getMetaData().getMeasureColumnNames().toArray(new String[0]);
String normalizedSubQuery = query;
normalizedSubQuery ="SELECT " + normalizedSubQueryAlias + "." + getMetaData().getGeoIdColumnName( hierarchy.getName() ) + " AS " + getMetaData().getGeoIdColumnName( hierarchy.getName() );
for(int i = 0; i < kpiColumnNames.length; i++) {
normalizedSubQuery += ", SUM(" + normalizedSubQueryAlias + "." + kpiColumnNames[i] + ") AS " + kpiColumnNames[i];
}
normalizedSubQuery += " \nFROM ( " + query + ") " + normalizedSubQueryAlias;
normalizedSubQuery += " \nGROUP BY " + normalizedSubQueryAlias + "." + getMetaData().getGeoIdColumnName( hierarchy.getName() );
System.out.println("\nNormalized query:\n" + normalizedSubQuery);
aggragateQuery += " \nFROM ( \n" + normalizedSubQuery + "\n ) " + subQueryAlias;
String dimGeoQuery = getDimGeoQuery();
System.out.println("\nDimGeo query:\n" + dimGeoQuery);
aggragateQuery += ", (" + dimGeoQuery + ") " + dimGeoAlias;
aggragateQuery += " \nWHERE " + subQueryAlias + "." + getMetaData().getGeoIdColumnName( hierarchy.getName() );
aggragateQuery += " = " + dimGeoAlias + "." + baseLevel.getColumnId();
aggragateQuery += " \nAND " + dimGeoAlias + "." + level.getColumnId() + " = '" + filterValue + "'";
}
System.out.println("\nExecutable query:\n" + aggragateQuery);