首页 > 解决方案 > ORACLE SQL 枢轴问题

问题描述

我正在尝试旋转 sql 结果。我需要在一个查询中完成这一切。下面告诉我 header_id 的标识符无效。我正在使用 Oracle 数据库。

代码

Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr
from item_history ih, item ci, contract ppd, 
header ch, group g, cd_std_type ct, cd_hos h, 
cd_std_hospital_cat ht
where ih.item_id = ci.item_id
and ih.header_id = ch.header_id
and ci.hos_id = h.hos_id
and ih.item_id = ci.item_id
and ch.user_no = ppd.user_no
and ppd.group_id = g.group_id
and ch.header_type = ct.header_type_id
and ci.hos_id = h.hos_id
and h.cat_id = ht.cat_id
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)

标签: sqloracle

解决方案


您的内部查询header_id在其投影中没有,因此枢轴子句没有该列可供使用。您需要将其添加为:

Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr,ih.header_id
---------------------------------------------------------------^^^^^^^^^^^^^
from ...
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)

或者:

Select * From (
select ppd.group_id,g.group_name, ct.type_desc,ht.hos_cat_descr,ch.header_id
---------------------------------------------------------------^^^^^^^^^^^^^
from ...
)
Pivot
(
count(distinct header_id) as Volume
For hos_cat_descr IN ('A')
)

哪个并不重要,因为这两个值必须相等,因为它们是连接条件的一部分。

您可以使用更简单的聚合而不是枢轴来实现相同的目标,但大概您确实在枢轴上做了更多的工作。


推荐阅读