簡體   English   中英

在多列的 1 行中顯示多條記錄

[英]Display multiple records in one 1 row with multiple columns

我有一個存儲用戶信息的表,例如:

在此處輸入圖像描述

我需要編寫一個查詢,以下列格式返回結果:

在此處輸入圖像描述

我嘗試為每個狀態做一個LEFT JOIN但這沒有用,關於如何獲得預期結果的任何想法?

如果狀態數是固定的,你可以這樣做

Select 
    id user_id,
    open_status,
    open_status_date,
    inprogress_status,
    inprogress_status_date,
    complete_status,
    complete_status_date
from
    (select user_id id from yourTable group by user_id) U left join  
    (select user_id id, status open_status, status_date open_status_date 
     from yourTable where status = 'Open') O on U.id = O.id left join  
    (select user_id id, status inprogress_status, status_date inprogress_status_date 
     from yourTable where status = 'InProgress') P on U.id = P.id left join
    (select user_id id, status complete_status, status_date complete_status_date 
     from yourTable where status = 'Complete') C on U.id = C.id 
Order by id

闖入內聯視圖並加入。 但這可能不是最有效的方法。

另請注意:如果每個用戶肯定至少具有“打開”狀態,您可以跳過第一個U內聯視圖並以O開頭

您想使用樞軸,如下所示:

    select * from test
    PIVOT(
        max(status_date)
        FOR status
        IN ( 
            'Open',
            'In Progress',
            'Complete'
        )
    )
order by user_id

假設每個用戶都有“打開”狀態

With
 open as (select * from table where status = 'Open'),
 inp as (select * from table where status = 'In Progress'),
 comp as (select * from table where status = 'Complete')
select o.user_id,o.status open_status, o.status_date open_status_date,i.status InProgress_status, i.status_date InProgress_status_date,c.status complete_status, c.status_date complete_status_date
from open o, inp i, comp c
where o.user_id=i.user_id(+)
and o.user_id=c.user_id(+)

暫無
暫無

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

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