Since you use PIVOT, the data is aggregated, so you only return one value for each broken column. You do not have columns in your subquery that are unique and used in the PIVOT grouping aspect to return multiple rows. For this you need some value. If you have a column with a unique value for each "group", you should use it or you can use a window function, such as row_number() .
row_number() will create a serial number for each value of FF.Name , if you have 2 col1 , you will create 1 for the row and 2 for the other row. Once this is included in your subquery, you now have a unique value that is used when aggregating your data, and you will return a few lines:
SELECT [col1],[col2],[col3] FROM ( SELECT FF.Name AS NamePiv, FV.Name AS Val1, rn = row_number() over(partition by ff.Name order by fv.Id) FROM FormFields FF JOIN FilledValues FV ON FF.Id = FV.FormFieldId ) x PIVOT ( MIN(Val1) FOR NamePiv IN ([col1],[col2],[col3]) ) piv;
See SQL Fiddle with Demo . Output:
| col1 | col2 | col3 | |------|------|------| | c | a | b | | e | f | d |
source share