복붙노트

[SQL] 열 값을 기준으로 선택 출력 값 - 문 'SELECT'을의 'IF'

SQL

열 값을 기준으로 선택 출력 값 - 문 'SELECT'을의 'IF'

SELECT id, amount FROM report

이 경우 I report.type = 'P'및 -AMOUNT 경우 report.type = 'N'에 상당 양일 필요는 없다. 어떻게 위의 질의에이를 추가하는 방법은 무엇입니까?

해결법

  1. ==============================

    1.

    SELECT id, 
           IF(type = 'P', amount, amount * -1) as amount
    FROM report
    

    http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html를 참조하십시오.

    상태가 null 인 경우 또한 처리 할 수 ​​있습니다. 널 량의 경우 :

    SELECT id, 
           IF(type = 'P', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount
    FROM report
    

    부품 IFNULL (양, 0) 수단 량이 널 복귀 량, 그렇지 0이 아니다.

  2. ==============================

    2.case 문을 사용합니다 :

    case 문을 사용합니다 :

    select id,
        case report.type
            when 'P' then amount
            when 'N' then -amount
        end as amount
    from
        `report`
    
  3. ==============================

    3.

    SELECT CompanyName, 
        CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
             WHEN Country = 'Brazil' THEN 'South America'
             ELSE 'Europe' END AS Continent
    FROM Suppliers
    ORDER BY CompanyName;
    
  4. ==============================

    4.

    select 
      id,
      case 
        when report_type = 'P' 
        then amount 
        when report_type = 'N' 
        then -amount 
        else null 
      end
    from table
    
  5. ==============================

    5.대부분의 간단한 방법은 IF를 사용하는 것입니다 (). 예 MySQL은 조건부 논리를 수행 할 수 있습니다. 기능 3 PARAMS 조건 OUTCOME TRUE, FALSE 결과 걸리면.

    대부분의 간단한 방법은 IF를 사용하는 것입니다 (). 예 MySQL은 조건부 논리를 수행 할 수 있습니다. 기능 3 PARAMS 조건 OUTCOME TRUE, FALSE 결과 걸리면.

    그래서 논리는

    if report.type = 'p' 
        amount = amount 
    else 
        amount = -1*amount 
    

    SQL

    SELECT 
        id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
    FROM  report
    

    전혀의이 +는 적이없는 경우 당신은 복근 ()를 건너 뛸 수 있습니다

  6. ==============================

    6.

    SELECT id, amount
    FROM report
    WHERE type='P'
    
    UNION
    
    SELECT id, (amount * -1) AS amount
    FROM report
    WHERE type = 'N'
    
    ORDER BY id;
    
  7. ==============================

    7.당신이 시도 할 수 있습니다

    당신이 시도 할 수 있습니다

     SELECT id , IF(type='p', IFNULL(amount,0), IFNULL(amount,0) * -1) as amount FROM table
    
  8. from https://stackoverflow.com/questions/5951157/if-in-select-statement-choose-output-value-based-on-column-values by cc-by-sa and MIT license