Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return column in separate row in SELECT statement

In my Customers table, I have PrimaryPhone and SecondaryPhone columns and I'm asked to return them in two separate rows. I also want to mention that in most cases, SecondaryPhone may not even have a value and in those cases, there's no need to return the second row.

So, here's the data coming from Customers table:

CustomerId  |  CompanyName      |  PrimaryPhone    |  SecondaryPhone
123            Acme, Inc.          307-555-1234       307-555-2345
234            DataCorp, Inc.   |  824-555-6547

My SELECT statement should return the following data:

CustomerId  | CompanyName     | Phone
123           Acme, Inc.        307-555-1234
123           Acme, Inc.        307-555-2345
234           DataCorp, Inc.    824-555-6547

I'd appreciate some pointers on how to show data from a column as a separate row. Thanks.

like image 745
Sam Avatar asked Apr 01 '19 14:04

Sam


People also ask

How do you separate multiple columns listed in a SELECT statement?

Using the SELECT Statement to Retrieve Data in SQL To retrieve multiple columns from a table, you use the same SELECT statement. The only difference is that you must specify multiple column names after the SELECT keyword, and separate each column by a comma.

How do you exclude a column from a selection statement?

COLUMNS table holds all information about the columns in your MySQL tables. To exclude columns, you use the REPLACE() and GROUP_CONCAT() functions to generate the column names you wish to include in your SELECT statement later.


2 Answers

CROSS APPLY would be a good fit here

Select CustomerId
      ,CompanyName
      ,B.*
 From Customers A
 Cross Apply (values (PrimaryPhone)
                    ,(SecondaryPhone)
             ) B(Phone)
  Where Phone is not null

-- EDIT forgot the WHERE

like image 66
John Cappelletti Avatar answered Oct 19 '22 23:10

John Cappelletti


You could try an union like this

SELECT
    CustomerId,
    CompanyName,
    PrimaryPhone as Phone,
FROM dbo.Customers
UNION 
SELECT
    CustomerId,
    CompanyName,
    SecondaryPhone as Phone,
FROM dbo.Customers
WHERE 
    SecondaryPhone IS NOT NULL
like image 34
HappyPengins Avatar answered Oct 19 '22 22:10

HappyPengins