developer tip

MySQL의 Case 문

optionbox 2021. 1. 5. 07:58
반응형

MySQL의 Case 문


다음과 같은 정의를 가진 ' tbl_transaction ' 이라는 데이터베이스 테이블이 있습니다 .

id INT(11) Primary Key
action_type ENUM('Expense', 'Income')
action_heading VARCHAR (255)
action_amount FLOAT

두 개의 열을 생성하고 싶습니다 : Income AmtExpense Amt.

비용 항목인지 소득 항목인지에 따라 출력이 올바른 열에 표시되도록 SQL 쿼리 만 사용하여 조건부로 열을 채울 수 있습니까?

예를 들면 :

ID        Heading         Income Amt       Expense Amt
1         ABC             1000             -
2         XYZ             -                2000

MySQL을 데이터베이스로 사용하고 있습니다. 이 작업을 수행하기 위해 CASE 문을 사용하려고합니다.

건배!


예, 다음과 같습니다.

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt

FROM tbl_transaction;

다른 답변에서 지적했듯이 MySQL에는 IF()덜 자세한 구문을 사용 하여이 작업을 수행 하는 기능 도 있습니다 . 나는 일반적으로 다른 곳에서 지원되지 않는 SQL에 대한 MySQL 특정 확장이기 때문에 일반적으로 이것을 피하려고합니다. CASE표준 SQL이고 다른 데이터베이스 엔진에서 훨씬 더 이식 가능하며, 이식 가능한 대안이 상당히 느리거나 덜 편리한 경우에만 엔진 별 확장을 사용하여 가능한 한 이식 가능한 쿼리를 작성하는 것을 선호 합니다.


MySQL에는 IF()다음 이 있습니다 .

SELECT 
  id, action_heading, 
      IF(action_type='Income',action_amount,0) income, 
      IF(action_type='Expense', action_amount, 0) expense
FROM tbl_transaction

사용해보십시오 IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

이것은 작동합니다.

select 
  id
  ,action_heading
  ,case when action_type='Income' then action_amount else 0 end
  ,case when action_type='Expense' then expense_amount else 0 end
from tbl_transaction

Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html

Invariably, I first use one when I want the other.


I hope this would provide you with the right solution:

Syntax:

   CASE  
        WHEN search_condition THEN statement_list  
       [WHEN search_condition THEN statement_list]....
       [ELSE statement_list]  
   END CASE

Implementation:

select id, action_heading,  
   case when
             action_type="Expense" then action_amount  
             else NULL   
             end as Expense_amt,   
    case when  
             action_type ="Income" then action_amount  
             else NULL  
             end as Income_amt  
  from tbl_transaction;

Here I am using CASE statement as it is more flexible than if-then-else. It allows more than one branch. And CASE statement is standard SQL and works in most databases.

ReferenceURL : https://stackoverflow.com/questions/15265874/case-statement-in-mysql

반응형