简体   繁体   中英

break out each unique value of a column into multiple columns then display in single row

In my actual data I have the following query

SELECT Sales Person,
        (CASE WHEN [ProductType] = 'car' THEN [GOAL_VOLUME]
          END) AS 'car Goal'
    , (CASE WHEN [ProductType] = 'boat' THEN [GOAL_VOLUME]
          END) AS 'boat Goal'
    , (CASE WHEN [ProductType] IN ('bike', 'scooter') THEN [GOAL_VOLUME]
          END) AS 'bike/scooter Goal'
FROM PRODUCT_GOALS

My current results are each Sales Person's name broken out 3 times into 3 rows with each row having only one non-NULL value for the Goal_Volume... I need everything on one row... Might need multiple subqueries to join against for each product? See image below.

enter image description here

Thanks for the help

You can use conditional aggregation:

SELECT [Sales Person]
    , MAX(CASE WHEN [ProductType] = 'car' THEN [GOAL_VOLUME]
          END) AS 'car Goal'
    , MAX(CASE WHEN [ProductType] = 'boat' THEN [GOAL_VOLUME]
          END) AS 'boat Goal'
    , MAX(CASE WHEN [ProductType] IN ('bike', 'scooter') THEN [GOAL_VOLUME]
          END) AS 'bike/scooter Goal'
FROM PRODUCT_GOALS
GROUP BY [Sales Person]

Almost the same query as yours, just added MAX and GROUP BY .

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