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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With