2016-11-15 60 views
0

所以我一直在這一段時間,我想我會問專家。我希望能夠將我的查詢結果重新放回一行,但對於我來說,我無法弄清楚這一點。在我的數據庫字段中,我有兩個扣除代碼2902和2903,兩者的數量都不相同。並非所有的回報將包含2903代碼,但大多數將包含2902代碼。我如何才能將返回帶回來,以便所有數據都在同一行中供員工使用? 我要找的輸出如下SQL查詢將所有數據帶回一行

NameLast,NameFirst,DeductionCode2902,deductionamt2902,deductioncode2903,deductionamt2903

而是像下面多行:

NameLast,Namefirst,Deductioncode2902,DeductionAmt2902

姓名姓,名第一,扣除代碼2903,扣除金額2903

數據庫中的數據格式:

enter image description here

Select 
pr_employ.namelast, 
pr_employ.namefirst, 
pr_employ_hist.deductioncode 
pr_employ_hist.deductionamt 
from pr_employ, pr_employ_hist 
Where pr_employ.namelast = pr_employhist.namelast and 
pr_employ_hist.deductioncode = ‘2902’ or pr_employ_hist.deductioncode =’2903’ 
Group by 
pr_employ.namelast, 
pr_employ.namefirst, 
pr_employ_hist.deductioncode 
pr_employ_hist.deductionamt 
+2

什麼是你的rdbms?谷歌爲'「PIVOT 」' –

+2

GROUP BY,但沒有聚合函數是沒有意義的... – jarlh

+2

下一次作爲文本張貼表數據,我們不能從圖像複製/粘貼。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)瞭解如何提高您的問題質量並獲得更好的答案。 –

回答

1

嘗試使用條件SUM()

DEMO

SELECT `namelast`, `namefirst`, 
     SUM(CASE WHEN `DeductionCode` = 2902 THEN `DeductionAmt` ELSE 0 END) as amt2902, 
     SUM(CASE WHEN `DeductionCode` = 2903 THEN `DeductionAmt` ELSE 0 END) as amt2903 
FROM Table1 
GROUP BY `namelast`, `namefirst` 

輸出

enter image description here