SQL中的IF / THEN语句

时间:2014-12-16 18:59:46

标签: sql sql-server excel

首先让我说我是编程新手。我有一个关于在Excel中使用IF / THEN语句进行分类的问题。我有这个:

visit_id        action
1   sale 
1   sale 
1   sale 
2   service
2   service
3   sale 
3   sale 
3   service

我想得到这个:

visit   category
1   sale 
2   service
3   both

感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

在以下情况下尝试使用案例:

SELECT visit_id,
       CASE
         WHEN Sum(CASE
                    WHEN action = 'sale' THEN 1
                    ELSE 0
                  END) = Count(*) THEN 'sale'
         WHEN Sum(CASE
                    WHEN action = 'service' THEN 1
                    ELSE 0
                  END) = Count(*) THEN 'service'
         ELSE 'both'
       END
FROM   table
--WHERE  action in('sale','service')
GROUP  BY visit_id 

假设您只有两种类型action,即saleservice

答案 1 :(得分:0)

嗯..有人开始在选择中写CASE,但后来删除了他的答案,我不知道为什么......那是CASE的用途,但你还需要另一步。

  • 首先,您需要根据您的条件对行进行实际分类,并将结果写入NEW,SEPARATE列。这就是CASE进入的地方
  • 然后,您需要对该条件进行分组并汇总结果
  • 然后,您需要将汇总的结果转换为您最终想要的内容

T-SQL方言中的示例:

第1步:

select
    visit_id,
    case action when 'sale' then 1 else 0 end as actionIsSale,
    case action when 'service' then 1 else 0 end as actionIsService
from fooTable

第2步:

select
    visit_id,
    max(actionIsSale) as hasSale,
    max(actionIsService) as hasService
from (previousquery)
group by visit_id

第3步:

select
    visit_id as visit,
    case
        when hasSale='1' and hasService='0' then 'sale'
        when hasSale='0' and hasService='1' then 'service'
        when hasSale='1' and hasService='1' then 'both'
        else '!WTF!'
    end as category
from (previousquery)

总结:

select
    step2.visit_id as visit,
    case
        when step2.hasSale='1' and step2.hasService='0' then 'sale'
        when step2.hasSale='0' and step2.hasService='1' then 'service'
        when step2.hasSale='1' and step2.hasService='1' then 'both'
        else '!WTF!'
    end as category
from
(
    select
        step1.visit_id,
        max(step1.actionIsSale) as hasSale,
        max(step1.actionIsService) as hasService
    from
    (
        select
            visit_id,
            case action when 'sale' then 1 else 0 end as actionIsSale,
            case action when 'service' then 1 else 0 end as actionIsService
        from fooTable

    ) as step1
    group by step1.visit_id

) as step2

注意#1:将部件粘合在一起时,我直接将这些步骤用作子查询,因此我必须指定别名(as step1as step2等)。这是T-SQL / SqlServer中的特定要求,您的数据库可能不在乎,但这无论如何都是好事。

注意#2:如果您不喜欢这样的子查询,您可以轻松地将所有子查询分成临时表或CTE或其他任何内容;重要的是在短步骤和简单操作中执行数据转换的想法

注意#3:这段代码可能有轻微的缺陷和语法错误,我已经一次性编写并且没有尝试执行它。但是你现在应该有了整体想法,并且应该很容易遵循并纠正任何位。

注意#4:在您了解它的工作原理之后,您可以尝试将其打包到更短的查询中,即将Step2和Step3折叠为单个表达式,并且您会注意到它可以打包它与Step1一样,在一个查询中完成所有这些操作。你会得到像 Deepak Pawar 这样的东西。而我的解决方案"与他相比可能看起来过于膨胀,特别是对于这个简单的问题,"扩展到新的列并聚合"诀窍适用于许多更复杂的情况;)

相关问题