SQLselect 和 pivot 取决于两列

SQLselect and pivot depending on two columns

我有两个表 table1,col1 和 table2,col2 和 col3 我正在尝试使用以下代码 select 他们:

select col1,col2,col3
from table1
inner join table2 on table1.id = table2.table1_id

它给了我如图所示的结果: selected result

我想得到这个结果:

Final result

我怎么能这样做? 提前致谢...

您可以尝试使用 "case when" 和 "group by",例如

 select col1,sum(case when col2=value1 then vluee1 end) as T1,
 sum(case when cols2=value3 then value3 end) as T2
 from table1
 inner join table2 on table1.id = table2.table1_id
 group by col1

如果您只需要 "T1"..."T5" 和 "Others" 列中的有限数量的值(例如,不超过 5 个),那么您的 select 可能看起来像

select col1, x2.*
from table1
cross apply (
  select [1],[2],[3],[4],[5],
         concat([6], ', '+[7], ', '+[8], ', '+[9], ', '+[10]) Others
  from (
    select col2, rs + row_number()over(partition by rs order by col2) rn
    from table2
      cross apply (select case when col3 = 'X' then 0 else 5 end rs)x1
    where table2.table1_id = table1.id
  )a pivot (max(col2) for rn in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10]))p
)x2

See demo here

否则你可能需要一个动态的 sql,正如蒂姆建议的那样。