Text values in a pivot table?

后端 未结 3 1367
悲哀的现实
悲哀的现实 2020-12-20 00:41

I have a table (in MySQL) with 3 columns:

Location    Category     Supplier

   A        Computers    Company X
   A        Printers     Company Y
   B               


        
3条回答
  •  执念已碎
    2020-12-20 01:26

    What you seek is often called a crosstab. This can be done statically like so:

    Select Location
        , Min( Case When Category = 'Computers' Then Supplier End ) As Computers
        , Min( Case When Category = 'Printers' Then Supplier End ) As Printers
        , Min( Case When Category = 'Software' Then Supplier End ) As Software
    From MyTable
    Group By Location
    

    However, if what you seek is to have a dynamic number of categories (and thus columns), this cannot be done natively in SQL. This later solution is called a dynamic crosstab. The best approach is either to build the SQL statement akin to the static version above in your middle-tier or using a reporting tool which will do the same.

提交回复
热议问题