2017-08-23 60 views
0

我的輸入數據如下所示 - 在此示例中,如何將表1轉換爲表2,其中第一行分爲3?我怎樣才能然後打開表2到表3,其中我總結3行到1和如何將SQL中的1行變爲多行,然後求和

表1

Task  |Month1 |Month1 plan in % |Month2 plan in % |Month3 plan in % 
-----------+-------+-----------------+-----------------+---------------- 
Data entry |Jun-17 |40    |40    |20 
Processing |Jul-17 |30    |70 
Delivery |Aug-17 |70    |30 

表2

Task  |Year |Month  |% work planned 
------------+-------+-----------+-------------- 
Data entry |2017 |June  |40 
Data entry |2017 |July  |40 
Data entry |2017 |August  |20 
Processing |2017 |July  |30 
Processing |2017 |August  |70 
Delivery |2017 |August  |70 
Delivery |2017 |September |30 

表3

Task  |Year |Month |Total % work completed 
------------+-------+-------+---------------------- 
Data entry |2017 |July |80 
Processing |2017 |July |30 
Delivery |2017 |July |0 
Data entry |2017 |August |100 
Processing |2017 |August |100 
Delivery |2017 |August |70 
+1

你應該選擇一個問題或其他。 –

+1

你正在使用哪些DBMS?什麼版本?請在問題中添加相關標籤。 –

回答

0

我不不知道你使用的是什麼類型的數據庫,所以我決定使用PostgreSQL。一些細節會有所不同,但這些想法應該適用於其他數據庫類型。

表#2可以用聯合產生。

例子:

select "Task", "Month1", "Month1 plan in %" from data                               
union                                           
select "Task", "Month1", "Month2 plan in %" from data                               
union                                           
select "Task", "Month1", "Month3 plan in %" from data 

爲了便於與數據的工作,別名合併後的數據集。像這樣:

select "Task", "Month1", "% work planned" from (
select "Task", "Month1", "Month1 plan in %" as "% work planned" from data 
union all 
select "Task", "Month1", "Month2 plan in %" as "% work planned" from data 
union all 
select "Task", "Month1", "Month3 plan in %" as "% work planned" from data 
) as combined where "% work planned" is not null; 

請注意,我添加了where條件來排除空值。這是因爲列3包含空值。

最後,您需要將字符串,字符串替換和CAST轉換爲日期,然後打印出該日期的月份。這裏有一個例子:

select to_char(
    (
    (substring('Jul-17', '...') || 
    '-01' || 
    substring('Jul-17', '...$'))::date 
    ), 
    'MONTH') AS MONTH; 

使用上表2的總和,產生表3

+0

感謝user1094125 - 表2適合我 - 這太棒了。我在MS SQL Mgmt工作室工作,使用to_char函數進行日期操作,雙冒號和管道對我來說並不熟悉。你可以請MSSQL詳細說,這將是偉大的... – texastonie