Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to divide a numeric column into two different columns based on a binary column?

I have a table in SQL Server that keeps track of hours and if they are billable or not.

SELECT 
    Billable,
    HoursBooked
FROM
    Time

Result:

Billable HoursBooked
--------------------
   0         8.0
   1         4.0
   1         6.0

I want to divide the hours into new columns based on whether it is billable or not. The new columns should be BillableHours and NonBillableHours.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Billable HoursBooked BillableHours NonBillableHours
----------------------------------------------------
   0         8.0          0.0            8.0
   1         4.0          4.0            0.0
   1         6.0          6.0            0.0

I figured out how to get billable hours by multiplying the two columns together, but this doesn’t work where billable = 0.

SELECT 
    Billable,
    HoursBooked
    Billable * HoursBooked AS BillableHours
FROM
    Time

Output:

Billable HoursBooked BillableHours
----------------------------------
   0         8.0          0.0
   1         4.0          4.0 
   1         6.0          6.0

What would be the best way to create the non-billable hours column?

>Solution :

You can do this:

SELECT Billable,
       HoursBooked
       Billable*HoursBooked AS BillableHours
       HoursBooked*(1-Billable) AS NonBillableHours
From Time

I would suggest you to use CASE statement here too, if it makes more sense:

SELECT Billable,
       Hoursbooked,
       CASE
         WHEN Billable = 1 THEN Hoursbooked
         ELSE 0
       END AS BillableHours,
       CASE
         WHEN Billable = 0 THEN Hoursbooked
         ELSE 0
       END AS NonBillableHours,
FROM Time; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading