SQL选择和透视取决于两列

时间:2017-12-19 06:34:42

标签: sql sql-server-2014 sql-server-2017

我有两个表table1,col1& table2 with col2和col3 我正在尝试以下代码来选择它们:

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

它给出了如下所示的结果: selected result

我想得到这个结果:

Final result

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

2 个答案:

答案 0 :(得分:0)

您可以尝试使用“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

答案 1 :(得分:0)

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

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,正如蒂姆建议的那样。