2

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?

0

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

You need to remove the extra "SELECT" before the CASE
True. Thanks @pmbAustin.
@MrLahey the best way to say thank you on SO is to accept the answer ;)
3

Use CASE

SELECT
  ServiceBase.User
  ,ServiceBase.Time
  ,ServiceBase.BillingType
  ,CASE WHEN ServiceBase.BillingType = 'Fixed' THEN ServiceBase.Time ELSE 0 END
from ServiceBase

Comments

3

You need to use the case when construct

SELECT
  ServiceBase.User
  ,ServiceBase.Time
  ,ServiceBase.BillingType
  ,case when ServiceBase.BillingType = 'Fixed' then ServiceBase.Time else 0 end
from ServiceBase

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.