Sql Server 2008 Cross Tab Query

后端 未结 2 831
滥情空心
滥情空心 2020-12-06 14:02

I usually can figure out any sql queries I need for my applications, but I have recently been stumped by a Cross Tab query I need to create and was wondering if you could he

2条回答
  •  北海茫月
    2020-12-06 14:42

    You should be able to do this with the 'pivot' operator. Something like this (though I am sure I muffed some spelling or syntax details...):

    select catTitle, [1] as site1, [2] as site2, [3] as site3, [4] as site4, [5] as site5
      from (select category.catTitle, equipment.quantity, site.title
              from equipment
                inner join site
                  on (equipment.siteid = site.siteid)
                inner join category
                  on (category.catid = equipment.catid)
            ) 
      pivot
      (
      sum (quantity)
        for equipment.siteid in ( [1], [2], [3], [4], [5] )
      ) as pvt
    order by pvt.category;
    

    The problem with this is that you need to know the exact set of site ids you want to include in the query. If you need a more dynamic crosstab (like you can get in Excel), then you need to generate the query text as a string and use sp_executesql to run it. In the generated text, you include as many of the "[1], [2], [3], [4], [5]..." and "[1] as site1, [2] as site2..." things as you need.

提交回复
热议问题