2016-04-13 24 views
0

我有一张表,看起来像下面,我想做2件事情。 1。选择最小(EnterDtm)记录,在这种情况下,这将是2015-08-25 05:29:44:480。我也希望有一个具有高度尺,高度英寸,重量(kg)作为新的列名,而新列的下方是ObsText多行与单行与多列与最小日期

EnterDtm     ObsCatalogName VisitID OBSTEXT 
2015-08-25 05:29:44.480 AS height feet NU 219975 5 
2015-08-25 05:29:44.480 AS height inches NU 219975 5 
2015-08-25 05:29:44.480 AS weight kg CAL 219975 88 
2015-08-25 07:05:11.173 AS weight kg CAL 219975 90.6 
2015-08-26 06:36:43.537 AS weight kg CAL 219975 90.5 
2015-08-26 21:22:21.550 AS height feet NU 219975 5 
2015-08-26 21:22:21.550 AS height inches NU 219975 6 
2015-08-26 21:22:21.550 AS weight kg CAL 219975 90.5 
2015-08-27 05:55:27.373 AS weight kg CAL 219975 87.4 

我希望它看起来像这样

EnterDtm     VisitID Height Feet Height Inches Weight 
2015-08-25 05:29:44.480 219975 5    5    88 
单个记录排
+0

如果您的引擎支持它,则3个case语句为max和group by或pivot。这是什么RDBMS? – xQbert

+0

SQL Server 2012 – user3666224

+0

因此,如果2015-08-25 07:05:11.173是最早的日期......您的高度数据不会正确吗? – xQbert

回答

0

首先,我使用case语句在公用表表达式With cte(可以轻松使用内联视图)中生成包含所需格式字段的一组数据。

这也通过使用基于日期和访问的amx将这些字段组合到一个记录中,并为日期排序的访问分配排名。

我再选择从CTE在秩为1(最低enterDTM)产生的数据集中的所有记录每个visitID

UNTESTED:

With CTE AS (
Select EnterDTM 
,OVisitID 
,max(case when OBSCatalogName = 'height feet NU' then OBStext end) as [Height Feet] 
,max(case when OBSCatalogName = 'height inches NU' then OBStext end as [Height Inches] 
,max(case when OBSCatalogName = 'weight kg CAL' then OBStext end as [Weight] 
Rank() over (partition by VisitID, EnterDTM order by enterDTM) RNK 
FROM TableName A 
GROUP BY EnterDTM, VisitID) 
Select from cte where RNK = 1 
0

你可以试试下面的透视查询

select 
EnterDtm, 
VisitID, 
[height feet NU] as [Height Feet], 
[height inches NU] as [Height Inches], 
[weight kg CAL] as [Weight] 
from 
(
    select 
    t.EnterDtm, 
    t.ObsCatalogName, 
    t.VisitID, 
    t.OBSTEXT 
from tbl t 
    inner join (select min(EnterDtm) MinDtm from tbl) t2 
    on t.EnterDtm=t2.MinDtm 
)source 
pivot 
(
max(OBSTEXT) for ObsCatalogName in ([height feet NU],[height inches NU],[weight kg CAL]) 
)p