Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross apply boolean values in SQL

I had the table below which I need to create a Category column will store the boolean values as a category.

enter image description here

I would like to capture the Categories as a single column and I don't mind having duplicate rows in the view. I would like the first row to return Contract and the second the other value selected, for the same Reference ID.

I achieved his using the query below:

select distinct t.*, tt.category
from t cross apply
     ( values ('Contracts', t.Contracts),
              ('Tender', t.Tender),
              ('Waiver', t.Waiver),
              ('Quotation', t.Quotation)
     ) tt(category, flag)
where flag = 1;

enter image description here

How can I capture an additional Category None where all instances of Contract, Tender, Waiver and Quotation are 0?

like image 260
Christopher Kinyua Avatar asked Apr 27 '26 08:04

Christopher Kinyua


2 Answers

None can go right into your VALUES clause. You case use a case expression for the logic. Alternatively, you can use a trick with sign():

select distinct t.*, tt.category
from t cross apply
     ( values ('Contracts', t.Contracts),
              ('Tender', t.Tender),
              ('Waiver', t.Waiver),
              ('Quotation', t.Quotation),
              ('None', 1 - sign(t.Contracts + t.Tender + t.Waiver + t.Quotation))
     ) tt(category, flag)
where flag = 1;

I am guessing that you don't have duplicates in your original table, so you should dispense with SELECT DISTINCT.

like image 110
Gordon Linoff Avatar answered Apr 29 '26 00:04

Gordon Linoff


Maybe something like this:

select distinct t.*, tt.category
from t cross apply
     ( values ('Contracts', t.Contracts),
              ('Tender', t.Tender),
              ('Waiver', t.Waiver),
              ('Quotation', t.Quotation),
              ('None', -1)
     ) tt(category, flag)
where flag = 1 or 
(Contracts = 0 and Tender = 0 and Waiver = 0 and Quotation = 0 and flag = -1);

Here's my sample fiddle (guessing you have bit fields, but it works with int fields too): http://sqlfiddle.com/#!18/9f8e7/1

like image 41
Vik Avatar answered Apr 29 '26 02:04

Vik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!