簡體   English   中英

SQL如何基於另一列中的值在一行中多次選擇列

[英]SQL How to select columns multiple times on one row based on value in other column

我需要根據以下四個表創建報告:

Table A: Columns(record_id, contact_id, role_id)

Table B: Columns(contact_id, fname, lname)

Table C: Columns(role_id,role_description)

Table D: Columns(Record_id, date)

查詢:

select d.record_id,d.date,b.fname,b.lname,c.role_description
from a,b,c,d
where a.contact_id = b.contact_id and
      a.role_id = c.role_id and
      a.role_id in('legal','finance') and
      a.record_id = d.record_id

該查詢將產生多行,如下所示:

Record ID | Date   | Fname | Lname | Role | 
=============================================
1         |Jan 2   | Bob   | Smith | Legal |
----------------------------------------------
1         |Jan 2   | Jim   | Jones | Finance |  
----------------------------------------------

我需要生產的是:

-----------------------------------------------------------------------------
record ID | Date  | Legal User | Finance User |       
--------------------------------------------------------------------
1         | Jan 2 |Bob Smith   | Jim Jones   |

我了解聯接和串聯,但無法弄清楚如何根據角色讓2個用戶排成一行。

SELECT *
FROM
    (
       select d.record_id,d.date
          ,b.fname + b.lname AS name
          ,c.role_description + ' User' as role_description
       from a,b,c,d
       where a.contact_id = b.contact_id and
            a.role_id = c.role_id and
            a.role_id in('legal','finance') and
            a.record_id = d.record_id
    ) q
    PIVOT 
    (
       MAX(name)
       FOR role_description IN ([Legal User], [Finance User])
    )

您應該可以使用PIVOT。 我知道這看起來很奇怪,因為您正在使用varchar的MAX(),但是這樣做確實可行。

根據您對未簡化的特定語法的評論,我可以這樣做:

SELECT *
FROM
    (
       select
          d.ctx_id
          ,effective_date,
          b.first_name + b.last_name AS name
          ,c.description
       from
          ctx_contract_contacts a
          INNER JOIN ctx_contacts b
          ON a.contact_id = b.contact_id
          INNER JOIN code_lookup c
          ON a.association = c.lookup_code 
          INNER JOIN ctx_basic_info d 
          ON a.ctx_id = d.ctx_id
       where
          and a.association in(117601,117759)
    ) q 

    PIVOT
    (
       MAX(name) 
       FOR description IN ([Legal Reviewer], [NDA reviewer])
    ) p
select d.record_id,d.date,
[legal user]=case role_id when 'legal' then b.fname +' '+b.lname
[Finance user]=case role_id when 'finance' then b.fname +' '+b.lname
from a,b,c,d
where a.contact_id = b.contact_id and
      a.role_id = c.role_id and
      a.role_id in('legal','finance') and
      a.record_id = d.record_id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM