2016-04-13 26 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