I've written a query on a table which contains a list of 'Statements' against 'Companies' like so (obviously simplified):
Statement | Company
---------------------------
ABC | CompA
ABC | CompB
DEF | CompC
The query presents the information like so:
Statement | CompA | CompB | Comp C
--------------------------------------
ABC | X | X |
DEF | | | X
Using the code like this:
SELECT
[Requirement_Text],
CASE WHEN(SUM(CASE WHEN Company = 'CompA' THEN 1 END)) IS NOT NULL THEN 'X' ELSE ' ' END AS CompA,
CASE WHEN(SUM(CASE WHEN Company = 'CompB' THEN 1 END)) IS NOT NULL THEN 'X' ELSE ' ' END AS CompB,
CASE WHEN(SUM(CASE WHEN Company = 'CompC' THEN 1 END)) IS NOT NULL THEN 'X' ELSE ' ' END AS CompC,
CASE WHEN(SUM(CASE WHEN Company IS NULL THEN 1 END)) IS NOT NULL THEN 'X' ELSE ' ' END AS NILL
FROM [StatementTable]
Now, this is easy enough because we have a finite number of companies, but if we were to say move it down to Department level (instead of Company) then we have several more (an unknown number - N).
So the question is, how can I create the columns in the output table based on the number of distinct values in a given column of the input table?
For example:
Statement | Company | Department
---------------------------------------
ABC | CompA | Dept(1)
DEF | CompA | Dept(2)
DEF | CompA | Dept(3)
GHI | CompA | Dept(3)
ABC | CompB | Dept(N-1)
DEF | CompC | Dept(N)
Will become:
Statement | Dept(1) | Dept(2) | Dept(3) | Dept(N-1) | Dept(N)
---------------------------------------------------------------
ABC | X | | | X |
DEF | | X | X | | X
GHI | | | X | |
NOTE: In this case I've disregarded the company name.
Thanks in advance.