多行到单行,其中多个列具有最小日期

时间:2016-04-13 21:41:01

标签: sql sql-server sql-server-2012

我有一张如下所示的表,我想做两件事。 1。选择Min(EnterDtm)记录,在本例中为2015-08-25 05:29:44:480。我还希望有一个高度为Feet,height inches和weight 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

2 个答案:

答案 0 :(得分:0)

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

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

然后我选择CTE中生成的数据集中的所有记录,其中每个visitID的等级为1(最低的enterDTM)

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 

答案 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