Sql Query将所有数据带回一行

时间:2016-11-15 15:53:36

标签: sql

所以我一直在研究这个问题,我想我会问专家。我希望能够将我的查询结果带回一行,但对于我的生活,我无法弄清楚这一点。在我的数据库字段中,我有两个扣除代码2902和2903都等于不同的金额。并非所有返回都包含2903代码,但大多数将包含2902代码。如何将退货返回以便员工的所有数据都在一行中? 我正在寻找的输出是以下

NameLast,NameFirst,DeductionCode2902,deductionamt2902,deductioncode2903,deductionamt2903

而不是像下面这样的多行:

NameLast,Namefirst,Deductioncode2902,DeductionAmt2902

NameLast,NameFirst,Deductioncode2903,DeductionAmt2903

数据库中的数据格式:

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

1 个答案:

答案 0 :(得分: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