Case statement with where condition in SQL

会有一股神秘感。 提交于 2020-01-17 06:16:09

问题


I am trying to write a CASE statement in SQL.

The DB structure is as follows:

==============================================
tender_id  |  file_no  |   subject
==============================================

150001         16/41        Against Shipment
150005         16/42        Pending
150008         16/43        Shipment Clause
1500081        16/43        NULL or Empty
1500082        16/43        NULL or Empty
==============================================

I am trying to write a CASE statement which shows the subject. The criteria is if Subject is NULL or EMPTY then it should fetch the subject where subject is entered with the criteria where file_no = file_no. In this case tender_id 1500081 and 1500082 should take the subject as 'Shipment Clause' since the file_no of those matches.

Can anyone help me on this?


回答1:


Sqlfiddle here

I have assumed first two column to be int you can change it according to your database and edit accordingly.

Assuming you will always have file_no in the table you search by file_no always which will give you the desired result

SELECT subject
FROM [table_name]
WHERE file_no = (SELECT file_no FROM [table_name] where tender_id = [required_tender_id])
AND subject IS NOT NULL;



回答2:


You can solve this with a self-join:

SELECT t1.tender_id, t2.file_no,
  CASE t1.subject 
  WHEN 'NULL or Empty' THEN t2.subject 
  ELSE t1.subject END AS subject
FROM YourTableName AS t1
JOIN YourTableName AS t2 
  ON (t2.file_no = t1.file_no AND t2.subject <> 'Null or Empty');

This assumes there is only one row where the subject is set, for each file_no.

Update: I created a SQLFiddle to demo this query. This satisfies the problem you described, as I understand it.



来源:https://stackoverflow.com/questions/41390604/case-statement-with-where-condition-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!