Pawan
Pawan

Reputation: 3864

MYSQL:Where condition in Case statement

I have table room_category_charges with fields like

id room_category(id) category_charges payment_type(id)
1       1                   300              1
2       1                   600              2
3       2                   400              1
4       2                   800              2

and there is another table patient_detail(patient_admission) where tpa(third_party_name) is selected. Whether or not tpa name is selected the rates of payment type varies.

Accordingly I am trying to use the following mysql query using case.

I want to return the charges

  1. as 600 where room_category is 1 and tpa_name is not null.
  2. as 400 where room_category is 2 and tpa_name is null

SQL:

  select rn.room_name, 
    CASE WHEN p.tpa_name is NULL
    THEN rcc.category_charges where rcc.payment_type=1
    ELSE rcc.category_charges where rcc.payment_type=2
    END AS 'charges'
  from estimate e,patient_detail p,room_name n

the where clause in then and else statement is generating the error, how I can incorporate the where clause in the case statement.

Thanks.

Upvotes: 1

Views: 166

Answers (2)

Pawan
Pawan

Reputation: 3864

Ok I found one solution, which seems to be working fine. Any better solution is welcome.

SELECT rn.room_name, rcc.category_charges
FROM estimate e,room_category rc, room_name rn, room_category_charges rcc, patient_detail p
WHERE rn.room_category = rc.id and rcc.room_category=rc.id
AND e.alloted_bed = p.bed_type
AND rcc.payment_type =2 and e.alloted_bed=rn.id and p.tpa_name is not null

union

SELECT rn.room_name, rcc.category_charges
FROM estimate e,room_category rc, room_name rn, room_category_charges rcc, patient_detail p
WHERE rn.room_category = rc.id and rcc.room_category=rc.id
AND e.alloted_bed = p.bed_type
AND rcc.payment_type =1 and e.alloted_bed=rn.id and p.tpa_name is null

Upvotes: 1

lp_
lp_

Reputation: 1178

where is a clause of the select statement and you cannot use it in a case operator.

The syntax of case can be as follows:

CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

As I understand the question, you might want a query like this

select rn.room_name, 
rcc.category_charges
from estimate e
join room_name rn on e.alloted_bed=rn.id
join patient_detail p on e.ipd_patient_id=p.ipd_patient_id
join room_category_charges rcc on rn.room_category=rcc.id and ((rcc.payment_type=1 and p.tpa_name is null) or (rcc.payment_type=2 and p.tpa_name is not null))

Upvotes: 0

Related Questions