简体   繁体   中英

How to use Select Distinct

I have database as follow :

npw  | sales_name | sales_type | Region |
-----------------------------------------
  1  |    Rob     | private 1  |   1    |
  2  |    Cait    | private 2  |   2    |
  3  |    Blue    | public     |   4    |
  4  |    ReD     | public     |   3    |
  5  |    Max     | private 1  |   2    |

and i want to make it look like :

region| private 1  | private 2  | public     |
-----------------------------------------------
  1   |     -      |      -     |      -     |
  2   |     -      |      -     |      -     |
  3   |     -      |      -     |      -     |
  4   |     -      |      -     |      -     |

so i want to distinct Region column as rows and distinct sales_type column as column header. In the future there's a possibility for new sales_type to be added. What SQL Query for it & make new sales_type added automatically to the new column header?

You can accomplish such result by CASE WHEN AND GROUP BY

SELECT 
     Region,
     CASE 
         WHEN sales_type = 'private 1' 
         THEN sales_type 
         ELSE '-' END AS 'private 1',
    CASE 
        WHEN sales_type = 'private 2' 
        THEN sales_type  
        ELSE '-' END AS 'private 2',
   CASE 
        WHEN sales_type = 'public' 
        THEN sales_type  
        ELSE '-' END AS 'public'
FROM your_table
GROUP BY Region;

try following

select Region, 
   case when sales_type in('private 1') then sales_name else '' end  private1, 
   case when sales_type in('private 2') then sales_name else '' end privat2, 
   case when sales_type in('public') then sales_name else '' end public
from Table1

check into sqlfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM