简体   繁体   English

能否在SQL查询中使用相同的列两次使用不同的过滤器?

[英]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. 在其中,我需要合并来自4个表的信息。 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. 我也可以复制该列,然后在excel中对其进行排序,但是客户需要能够自己完成此操作,而无需在以后进行编辑。

    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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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