在我的实际数据中,我有以下查询
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
我当前的结果是每个销售人员的名字分成3行,分为3行,每行的Goal_Volume值只有一个非NULL值...我需要一行中的所有内容...可能需要多个子查询才能加入每个产品? 参见下图。
感谢您的帮助
答案 0 :(得分:0)
您可以使用条件聚合:
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]
与您的查询几乎相同,只是添加了MAX
和GROUP BY
。