SQL:条件测试

时间:2016-11-24 22:19:56

标签: mysql

我想在两个计数器上测试2个条件。样本:

@verifier = ActiveSupport::MessageVerifier.new('s3Krit')
cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
id, time = @verifier.verify(cookies[:remember_me])

我'预计会有

 id_client | zipcode     | timestamp               | UC     | MISS
--------------------------------------------------|--------|------
amar      | 11111       | 2016-09-28 20:05:03.001 | 15     | 0
akbar     | 11111       | 2016-09-28 20:05:03.001 | 50     | 1  
antony    | 11111       | 2016-09-28 20:07:03.001 | 110    | 0
amar      | 11111       | 2016-09-28 20:08:03.001 | 5      | 1

select
  date (CollectionTime) as dates,
  id_client
  case when UC <=15 THEN 'TB'
    UC < 15 THEN 'TB'
    UC > 15  AND UC <=40 THEN 'B'
    UC >40  AND  UC <=80 THEN 'M'
    UC > 80 THEN 'TM'
    ELSE 'NULL' END AS tranche_UC
  case when MISS = O THEN 'BONNE'
  MISS =1 THEN 'Mauvaise'
  ELSE 'NULL' END AS note
from cm_stat 
group by id_client
order by dates;

1 个答案:

答案 0 :(得分:2)

您的查询建议您希望最后一列为bonnemauvais而不是1或0,如示例所示。我会选择bonne和mauvais。

首先你有一些语法错误:

  1. id_client
  2. 之后缺少逗号
  3. WHEN
  4. 中的每个条件都需要CASE

    这是没有语法错误的查询:

    select
      date (CollectionTime) as dates,
      id_client, -- missing comma
      case
        when UC <=15 THEN 'TB'
        when UC < 15 THEN 'TB' -- needed WHEN (use before every condition)
        when UC > 15  AND UC <=40 THEN 'B' -- needed WHEN
        when UC >40  AND  UC <=80 THEN 'M' -- needed WHEN
        when UC > 80 THEN 'TM' -- needed WHEN
        ELSE 'NULL' END AS tranche_UC
      case
        when MISS = O THEN 'BONNE'
        when MISS =1 THEN 'Mauvaise' -- needed WHEN
        ELSE 'NULL' END AS note
    from cm_stat 
    group by id_client
    order by dates;
    

    现在语法已全部设置,您有一些逻辑错误:

    1. UC逻辑过度(例如,检查&lt; = 15 &lt; 15以返回TB
    2. 我不明白为什么你有group by id_client
    3. 所以这里是逻辑理顺的查询:

      select
        date (CollectionTime) as dates,
        id_client,
        case
          when UC <=15 THEN 'TB'
          when UC <=40 THEN 'B'
          when UC <=80 THEN 'M'
          when UC > 80 THEN 'TM'
          ELSE 'NULL' END AS tranche_UC
        case
          when MISS = O THEN 'BONNE'
          when MISS = 1 THEN 'Mauvaise'
          ELSE 'NULL' END AS note
      from cm_stat
      order by dates;