user3533673
user3533673

Reputation: 3

Populating columns with a value based on a condition

I have a table containing fields called 'Category' and 'TotalTime'. When I run a query, I need to generate two additional temporary columns called 'Cat1Time'and 'Cat2Time'.

If the total time in a row is 4 hours and it is category 1, it should display a '4' under the Cat1Time column. If the total time in a row is 4 hours and it is category 1, it should display a '4' under the 'Cat2Time' column. Is there a way to do this?

EntryID | Category | Cat1Time | Cat2Time
2       |  1       |   4      |    
3       |  2       |          |   4
4       |  1       |   2.5    |   




Select EntryID, Category, TotalTime AS Cat1Time 
WHERE Category =1, TotalTime as Cat2Time where Category = 2 
from LogEntry

Anyways, I know that won't work... it's just to give you an idea what I am trying to do. Any help would be greatly appreciated!

Upvotes: 0

Views: 21

Answers (1)

Rhumborl
Rhumborl

Reputation: 16609

You need a CASE statement:

SELECT EntryID, Category, TotalTime,
    CASE WHEN Category = 1 THEN
        TotalTime
    ELSE
        NULL
    END AS Cat1Time,
    CASE WHEN Category = 2 THEN
        TotalTime
    ELSE
        NULL
    END AS Cat2Time 
FROM LogEntry

Upvotes: 1

Related Questions