sql server选择结果作为列名

时间:2017-10-05 18:11:24

标签: sql-server

我在SQL Server 2016 Express中有这个表

TestDate    TestCode    TestResult
2017-08-30  HGB         5.3       
2017-09-01  HGB         6.1       
2017-09-03  HGB         6.8       
2017-09-06  HGB         7.9       
2017-09-13  HGB         8.5       
2017-08-30  EOS%        48.3      
2017-09-01  EOS%        47.1      
2017-09-03  EOS%        46.4      
2017-09-06  EOS%        47.3      
2017-09-13  EOS%        38.9      

我需要一个查询来返回如下结果:

TestDate    HGB     EOS%
2017-08-30  5.3     48.3      
2017-09-01  6.1     47.1      
2017-09-03  6.8     46.4      
2017-09-06  7.9     47.3      
2017-09-13  8.5     38.9      

Sql Table And Results

以下是创建&的代码填充表格

Create Table TestResult 
(
 TestDate   Datetime,
 TestCode   Char(10), 
 TestResult Char(10) 
)   

Insert Into TestResult Values('2017/08/30','HGB','5.3') 
Insert Into TestResult Values('2017/09/01','HGB','6.1') 
Insert Into TestResult Values('2017/09/03','HGB','6.8') 
Insert Into TestResult Values('2017/09/06','HGB','7.9') 
Insert Into TestResult Values('2017/09/13','HGB','8.5') 

Insert Into TestResult Values('2017/08/30','EOS%','48.3') 
Insert Into TestResult Values('2017/09/01','EOS%','47.1') 
Insert Into TestResult Values('2017/09/03','EOS%','46.4') 
Insert Into TestResult Values('2017/09/06','EOS%','47.3') 
Insert Into TestResult Values('2017/09/13','EOS%','38.9') 

1 个答案:

答案 0 :(得分:0)

试试这个:

- 修改类型testresult列

Create Table TestResult 
(
 TestDate   Datetime,
 TestCode   Char(10), 
 TestResult decimal(10, 2) 
)   

Insert Into TestResult Values('2017/08/30','HGB',5.3) 
Insert Into TestResult Values('2017/09/01','HGB',6.1) 
Insert Into TestResult Values('2017/09/03','HGB',6.8) 
Insert Into TestResult Values('2017/09/06','HGB',7.9) 
Insert Into TestResult Values('2017/09/13','HGB',8.5) 
Insert Into TestResult Values('2017/08/30','EOS%',48.3) 
Insert Into TestResult Values('2017/09/01','EOS%',47.1) 
Insert Into TestResult Values('2017/09/03','EOS%',46.4) 
Insert Into TestResult Values('2017/09/06','EOS%',47.3) 
Insert Into TestResult Values('2017/09/13','EOS%',38.9) 

select f1.TestDate, 
sum(case when f1.testcode='HGB' then f1.testresult else 0 end) HGB,
sum(case when f1.testcode='EOS%' then f1.testresult else 0 end) EOS
from TestResult f1
group by f1.TestDate

如果您无法修改类型列,请尝试以下方法:

select f1.TestDate, 
max(case when f1.testcode='HGB' then f1.testresult else 0 end) HGB,
max(case when f1.testcode='EOS%' then f1.testresult else 0 end) EOS
from TestResult f1
group by f1.TestDate