-1

有没有办法在 PIVOTED 列中有一个 CASE SELECT 语句。我的代码如下

SELECT PName, [RN], [HA], [LVN], [MSW], [SC] 
FROM 
(
   Query

 ) src 

  pivot
    (
     max(Visits)
    for Discipline in ([RN], [HA], [LVN], [MSW], [SC])
    ) piv

我得到的输出如下

   Pname        RN         HA          LVN        MSW        SC
    AA        AG-2/W    LO-1/W       NA-1/W     SK-2/W     NO-2/MON
    AA        JL-2/W     NULL         NULL        NULL       NULL

因为已经有 2 个 RN 分配给 1 个 PN,所以我想仅在 1 Row 中汇总结果,并仅选择 1 个值显示在 RN 列中,因此根据我的情况,结果仅如下所示。

    Pname        RN         HA          LVN        MSW        SC
    AA        JL-2/W    LO-1/W       NA-1/W     SK-2/W     NO-2/MON
4

2 回答 2

1

在没有看到完整查询的情况下,您应该能够将 row_number 应用于内部查询,然后使用WHERE类似于以下的子句:

SELECT PName, [RN], [HA], [LVN], [MSW], [SC] 
FROM 
(
   <yourQuery>, row_number() over(order by somefield) rn -- add a rownumber here
 ) src 
pivot
(
    max(Visits)
    for Discipline in ([RN], [HA], [LVN], [MSW], [SC])
) piv
where rn = 1

如果您发布完整的查询,可能还有其他方法可以做到这一点。

编辑,使用上一个问题中的信息,您的查询将如下所示:

select patname, [HA], [MSW], [RN]
from 
(
  select patName, Disc,
    sname+' '+schedule new_value,
    row_number() over(partition by patname, disc order by disc) rowNum
  from yourquery
) src
pivot
(
  max(new_value)
  for disc in ([HA], [MSW], [RN])
) piv
where rownum = 1

请参阅带有演示的 SQL Fiddle

或者您可以使用:

select *
from 
(
    SELECT PName, [RN], [HA], [LVN], [MSW], [SC] , row_number() over(partition by PName order by PName) rn
    FROM 
    (
       <yourQuery>
     ) src 
    pivot
    (
        max(Visits)
        for Discipline in ([RN], [HA], [LVN], [MSW], [SC])
    ) piv
) x
where rn = 1
于 2012-11-08T18:35:15.857 回答
0

您必须在透视后删除数据,因为 [RN] 本身受制于 MAX 条件,即它本身就是一个透视列。将其包装在 CTE 中,应用 RowNumber() 函数并正确分区,然后将其过滤为每个分区仅 1 行。

;WITH CTE AS (
    SELECT PName, [RN], [HA], [LVN], [MSW], [SC],
           ROW_NUMBER() OVER (partition by PName order by [RN] ASC) RowNum
    FROM 
    (
       Query

     ) src 

      pivot
        (
         max(Visits)
        for Discipline in ([RN], [HA], [LVN], [MSW], [SC])
        ) piv
)
SELECT *
  FROM CTE
 WHERE RowNum = 1;
于 2012-11-08T19:46:24.347 回答