SQL row value as column name

后端 未结 1 1946
鱼传尺愫
鱼传尺愫 2021-01-15 01:45

I\'m pretty experienced in C#, but still mostly a beginner in SQL.
We have an application in C#, using an MSSQL database.
One part of our application is simply a lis

1条回答
  •  一整个雨季
    2021-01-15 02:51

    You need to use pivot. One issue that may give you problems is that you must know how many categories you have since a query can't ever return a dynamic number of columns (not even one that you're pivoting).

    I don't have your schema, but this should be about right (may take a few touchups here and there, but it should get you started)...

    select
      Date, [1] as Cat1, [2] as Cat2, [3] as Cat3, ...
    from
      (select date, category from table) p
    pivot (
      count(*)
    for
      Category in ([1],[2],[3],...)
    ) pivoted
    order by
      pivoted.date
    

    0 讨论(0)
提交回复
热议问题