Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select IF another fields value is a specific string

I have an application that automatically tallies up the time spent for each user. Each user

Here is the query

SELECT
  ServiceBase.User
  ,ServiceBase.Time
  ,ServiceBase.BillingType
from ServiceBase

And here is the output

User 1  | Time
User 2  | Time
User 3  | Time
        | Total Time

I'm looking to add another column that splits the Time based on a BillingType without editing the actual application code. It will read in a new select field and automatically tally the values, so Im hoping to just use an IF inside the query to get my results to show in the application.

Something along the lines of:

SELECT
  ServiceBase.User
  ,ServiceBase.Time
  ,ServiceBase.BillingType
  ,Select If(ServiceBase.BillingType = 'Fixed'){ echo ServiceBase.Time; }else{ echo 0;}
from ServiceBase

To get a result like so:

User 1  | Time           | Fixed Time
User 2  | Time           | Fixed Time
User 3  | Time           | Fixed Time
        | Total Time     | Total Fixed Time

How can I do this in SQL?

like image 605
Mr Lahey Avatar asked Jul 19 '26 13:07

Mr Lahey


1 Answers

What you need is CASE for IFs within a SELECT statement:

SELECT
  ServiceBase.User
  ,ServiceBase.Time
  ,ServiceBase.BillingType
  ,CASE WHEN ServiceBase.BillingType = 'Fixed' THEN ServiceBase.Time ELSE 0 END AS [Fixed Time]
FROM ServiceBase
like image 184
Greg Viers Avatar answered Jul 22 '26 03:07

Greg Viers