Reputation: 601
I will present a question about 'aliasing' values from a column. I will use days of the week as an intuitive example to get my question across, but I am not asking for datetime conversions.
Suppose I have the following SQL script:
SELECT DaysOfWeek
FROM [databasename].[dbo].[tablename]
Now, the column DaysOfWeek
will return string values of the days' names, i.e. "Monday," "Tuesday," and so forth.
What if I wanted the query to return the integer 1 for 'Monday', 2 for 'Tuesday', and so forth? I would want to assign a particular value to each of the week's days in the SELECT
statement, but I'm not sure how to go about doing that.
I'm relatively new to SQL, so I just thought I'd ask for an intuitive method to perform such a task.
Edited to add: I'm only using days of the week and their respective integer representation as an easy example; my task does not involve days of the week, but rather employee code numbers and corresponding titles.
Upvotes: 4
Views: 19665
Reputation: 38023
If you wanted to define your own corresponding value for another value, the best way is to use a table, and join that table.
For example:
create table dbo.EmployeeTitle (
id int not null identity(1,1) primary key
, title varchar(32)
);
create table dbo.Employee (
id int not null identity(1,1) primary key
, name nvarchar(128)
, title_id int references dbo.EmployeeTitle(id)
);
insert into dbo.EmployeeTitle values ('Big boss');
insert into dbo.Employee values ('daOnlyBG',1);
select e.*, et.title
from dbo.Employee e
inner join dbo.EmployeeTitle et
on e.title_id = et.id
rextester demo: http://rextester.com/FXIM78632
returns:
+----+----------+----------+----------+
| id | name | title_id | title |
+----+----------+----------+----------+
| 1 | daOnlyBG | 1 | Big boss |
+----+----------+----------+----------+
Upvotes: 1
Reputation: 1123
The easiest way I can think of is to have a table variable or CTE; create your lookup as rows and join to it. Something like this:
with cte as (
select 1 as emp_code, 'value1' as emp_title
union
select 2 as emp_code, 'value2' as emp_title
union
select 3 as emp_code, 'value3' as emp_title
)
select cte.emp_code, tableName.*
from tableName
inner join cte
on cte.emp_title = tableName.some_column
Upvotes: 0
Reputation: 745
Use CASE, here you have the definition and one example :
select
CASE
WHEN(DaysOfWeek="Monday") THEN 1
WHEN(DaysOfWeek="Thusday") THEN 2
....
ELSE -1
from table
Hope this help!
Upvotes: 1
Reputation: 1269503
You can do this using case
:
SELECT (CASE DaysOfWeek
WHEN 'Monday' THEN 1
WHEN 'Tuesday' THEN 2
. . .
END)
Under most circumstances, it is unnecessary to store the day of the week like this. You can readily use a function, datepart()
or datename()
, to extract the day of the week from a date/time value.
If the column is in a table, and not part of a date, then you might want to include the above logic as a computed column:
alter table t add DayOfWeekNumber as (case DaysOfWeek when 'Monday' then 1 . . .);
Upvotes: 9