Parameterize the Columns in a PIVOT Query?

LabKey Support Forum (Inactive)
Parameterize the Columns in a PIVOT Query? Ben Bimber  2015-11-05 12:01
Status: Closed
 
Pivot queries are very useful, but it's really common for the pivot to produce a ridiculously large list of columns. Take this example: you have a table listing lab test results. There are a lot of potential values for the type of test. Any given patient only has a finite number of test records. if you write the standard PIVOT, the list of columns will be any available test, and does not by default do anything smart to limit to only those columns with data in the selected rows. I was hoping parameterized queries would give me an out - no luck.

Below is an example of SQL I'm trying to use. Is there a way to modify this such that the list of columns will be anything less than every possible value in the whole table? Thanks in advance:

PARAMETERS(SPECIES CHAR default NULL, LOCUS CHAR default NULL, CATEGORY CHAR default NULL)

SELECT
  a.analysis_id,
  a.lineages,
  sum(a.percent) as percent

FROM sequenceanalysis.alignment_summary_by_lineage a

GROUP BY a.analysis_id, a.lineages
PIVOT percent BY lineages in (
  SELECT DISTINCT r.lineage FROM sequenceanalysis.ref_nt_sequences r
  WHERE r.lineage is not null

--this is my attempt to filter the list of allowable columns based on the query params. does not appear to work.
    AND (r.species = SPECIES OR SPECIES is null)
    AND (r.locus = LOCUS OR LOCUS is null)
    AND (r.category = CATEGORY OR CATEGORY is null)
  ORDER BY r.lineage
)
 
 
jeckels responded:  2015-11-06 10:15
Hi Ben,

I don't think this is possible. In my attempts to combine parameterized queries and PIVOT BY, I get an error:

When used with parameterized query, PIVOT requires an explicit values list

Is this what you're seeing as well?

Underneath, the issue is that when we resolve the list of potential PIVOT values, we don't have the full context to know the parameter values. We need to know the shape of the results outside of having the parameters, so that we can do things like render the schema browser, etc.

While it's not as elegant, could you dynamically build the SQL with the parameter values embedded in your use case?

Thanks,
Josh
 
Ben Bimber responded:  2015-11-06 10:19
yeah, that matches what i see, and i agree w/ the reason why. in my paramterized example above, i gave them default values (null), which i why i think LabKey allows that query. I assume it evaluates the PIVOT column list using those default parameter values.

and yes, i ended up doing the less elegant solution of building SQL client-side and using executeSql to get my data.

thanks.