有没有办法在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个PN分配了2个RN,所以我想仅在1行中汇总结果,并且只选择1个值显示在RN列中,以便根据我的条件得出结果如下。
Pname RN HA LVN MSW SC
AA JL-2/W LO-1/W NA-1/W SK-2/W NO-2/MON
答案 0 :(得分: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
或者您可以使用:
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
答案 1 :(得分:0)
您必须在旋转之后删除数据,因为[RN]本身受MAX条件限制,即它本身就是一个枢轴列。将其包装在CTE中,应用RowNumber()函数并正确分区,然后对每个分区仅过滤一行。
;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;