带别名的案例陈述

时间:2016-03-12 21:04:49

标签: sql sql-server select case

我需要创建一个包含用户ID和指定值的表。我有这三个选择语句:

select sales_person_id from promotions where 
sales > 30000 and city = ‘Georgia’ 

select sales_person_id from promotions
where sales > 50000 and city = ‘Atlanta’

select sales_person_id from promotions
where sales > 25000 and city = ‘Tampa’

基本上我需要它来显示select语句一,表是否包含user_id和value = 10 如果select语句两个user_id和value = 5 如果选择语句三user_id和value = 7

我尝试使用带有别名的case语句来获取一个名为value的列而没有运气。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

只需将where条款中的条件转换为when表达式中的case条件:

SELECT sales_person_id,
       CASE WHEN sales > 30000 AND city = 'Georgia' THEN 10
            WHEN sales > 50000 and city = 'Atlanta' THEN 7
            WHEN sales > 25000 and city = 'Tampa'   THEN 5
       END AS value
FROM   promotions