Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create/add a column in an SQL select query based on another column's values?

Tags:

sql

select

mysql

I want to dynamically add another column hook_name, via an SQL select query, based on a condition.

For example if hook_type = 0, table hook_name should have a value of OFFER, and similarly for hook_type = 1, hook_name should show "ACCEPT".

Below is a screenshot of the result:

enter image description here

The select query is this:

select hook_type, 'hook name' as hook_name,
       count(*) as number_of_exchange_activities 
from `exchange` 
group by hook_type # hook_type 0 for OFFER, 1 for ACCEPT and 2 for offer EXPIRED;

Thanks in advance.

like image 453
Ahsan Zaheer Avatar asked Aug 19 '13 11:08

Ahsan Zaheer


People also ask

How do you create add a column in SQL select query based on another column values?

In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.

How do you create a column in SQL with conditions?

Syntax. The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.

How do I add a column to a SQL table after a specific column?

Syntax. The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name.

How do you add a column to a specific position in an existing table in SQL?

To add a column at a specific position within a table row, use FIRST or AFTER col_name . The default is to add the column last. You can also use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns within a table.


2 Answers

Use a Standard SQL CASE:

SELECT hook_type, 
   CASE hook_type
      WHEN 0 THEN 'OFFER'
      WHEN 1 THEN 'ACCEPT'
      WHEN 2 THEN 'EXPIRED'
   END AS hook_name,
   COUNT(*) AS number_of_exchange_activities 
FROM `exchange` 
GROUP BY hook_type
like image 131
dnoeth Avatar answered Oct 12 '22 13:10

dnoeth


select case when hook_type = 0 then 'offer'
            when hook_type = 1 then 'accept'
            else 'expired'
       end as hook_t, 
      `hook name` as hook_name,
      count(*) as number_of_exchange_activities 
from `exchange` 
group by hook_t

BTW I think you want to escape the column name hook name. Then use backticks and not quotes.

like image 26
juergen d Avatar answered Oct 12 '22 14:10

juergen d