2015-09-30 33 views
-2

我想在sql server 2005中將三行組合爲單行,我嘗試過使用group by子句,但我無法將三行組合成單行無法在sql中按行組合

下面是代碼,我自己編寫

 
select * from 
(
select 
    case 
    when postatus = 'y' and approverid = '1111' 
    then Convert(varchar(10), trasdate ,103) 
    end as [col1], 
    case 
    when postatus = 'y' and approverid = '401' 
    then Convert(varchar(10), trasdate ,103) 
    end as [col2], 
    case 
    when postatus = 'y' and (approverid = '329' or approverid = '1495' or approverid = '1239') 
    then Convert(varchar(10), trasdate ,103) 
    end as [col3] 
from tblpo_approvalstatus where prnumber = '000002' 
) as t 
group by 
col1,col2,col3 

我得到的結果作爲

 
col1  col2  col3 
9/6/2015 NULL  NULL 
NULL  9/8/2015 NULL 
NULL  NULL  9/15/2015 

我希望他們作爲一個單列

 
col1  col2   col3 
9/6/2015 9/8/2015  9/15/2015 

在此先感謝

+0

請張貼你試過的東西。 –

+0

@Thorsten,在結果中,我希望單行爲2 fgh cde abc,謝謝 – Kumar

+0

並且如果col1 = 3的記錄也存在,你想要兩個結果行,一個是2,一個是3,還是隻有一個?如果有一個:你預計col1的值是多少?那麼如果col1 = 2有兩個記錄col2有兩個不同的值,比如說fgh和ijk:你會顯示哪個值? –

回答

0

你試試這個?

select no, max([po date]), max([pr date]), max([qar date]) 
from t 
group by no; 
0

您想聚合您的數據,因此請使用聚合函數。在你的情況下,每列只有一個值(因爲prnumber + postatus + + approverid在該表中是唯一的?也許他們構建主鍵?),您可以使用MIN或MAX甚至AVG,但沒有區別。

select 
    convert(varchar(10), max(case when postatus = 'y' and approverid = '1111' then trasdate end) ,103) as col1, 
    convert(varchar(10), max(case when postatus = 'y' and approverid = '401' then trasdate end) ,103) as col2, 
    convert(varchar(10), max(case when postatus = 'y' and approverid in ('329','1495','1239') then trasdate end) ,103) as col3 
from tblpo_approvalstatus 
where prnumber = '000002'; 

順便說一句,GROUP BY在這裏絕對不合適。用GROUP BY x, y表示「請彙總我的數據,使我得到每個x和y的結果行」,但您不希望每得到一個結果行;你想要一個結果行在所有(所以不是GROUP BY)。

+0

非常感謝你,我在表中獲取結果,我試圖把代碼放在存儲過程中,非常感謝 – Kumar