简体   繁体   中英

Can I use same column twice with different filters in sql query?

I am creating a report for a customer. In it I need to combine information from 4 tables. It's all fine until the last table, where I use just one column. This column contains phones and emails (all in one). I need to display email address and phone number in separate column, but they come from the same column.

I can display both but they show in separate rows. I can also duplicate the column and then sort it out in excel but customer needs to be able to do it themselves without editing it after.

    SELECT CustomerProcessO.GID,
           CustomerProcessO.FOIF,
           Customers.FirstName,
           Customers.LastName,
           SalesPersons.FirstName,
           SalesPersons.LastName,
           DynamicListData.DataContent AS Email,
           DynamicListData.DataContent AS Phone
      FROM CustomerProcessO
LEFT OUTER JOIN Customers ON CustomerProcessO.id = Customers.id
LEFT OUTER JOIN SalesPersons ON CustomerProcessO.GIDSalesPerson = SalesPersons.GID
LEFT OUTER JOIN DynamicListData ON ParentId = Customers.id
     WHERE DynamicListData.KeyField = 'EMAILS'
        OR DynamicListData.KeyField = 'PHONES'

The results I'm getting are correct but I get phone numbers and emails in two separate rows. I need to have one column with email and one column with phone number

You can join the same table twice:

SELECT dld1.DataContent AS Email, dld2.DataContent AS Phone
...
LEFT JOIN DynamicListData dld1 ON dld1.ParentId = Customers.id AND dld1.KeyField = 'EMAILS'
LEFT JOIN DynamicListData dld2 ON dld2.ParentId = Customers.id AND dld2.KeyField = 'PHONES'
SELECT        CustomerProcessO.GID, CustomerProcessO.FOIF, Customers.FirstName, Customers.LastName, SalesPersons.FirstName, SalesPersons.LastName, 
DLD1.Phone, DLD2.Email
FROM            CustomerProcessO 
LEFT OUTER JOIN Customers ON CustomerProcessO.id = Customers.id 
LEFT OUTER JOIN SalesPersons ON CustomerProcessO.GIDSalesPerson = SalesPersons.GID 
LEFT OUTER JOIN (SELECT ParentId, KeyField, DataContent AS [Phone] FROM DynamicListDate) DLD1 ON DLD1.ParentId = Customers.id AND DLD1.KeyField = 'PHONES'
LEFT OUTER JOIN (SELECT ParentId, KeyField, DataContent AS [Email] FROM DynamicListDate) DLD2 ON DLD2.ParentId = Customers.id AND DLD2.KeyField = 'EMAILS'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM