【问题标题】:Case statements with alias带别名的 case 语句
【发布时间】:2016-03-12 21:04:49
【问题描述】:

我需要创建一个带有用户 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’

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

我尝试使用带有别名的 case 语句来获取名为 value 的列,但没有成功。任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server select case


    【解决方案1】:

    只需将where 子句中的条件转换为case 表达式中的when 条件即可:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多