我在oracle中使用数据透视表时出现问题。我有一个工作示例,可以获取某些库存项目的计数。有两种类型的计数,但我只考虑一种类型。我需要改变我的例子以包含两种类型的计数并保持数据"在线"彼此(如果这是有道理的)。我会尽力解释。请考虑以下查询:
select *
from ( select state_code, city_code, equipment_type, sum(AVAILABLE_COUNT) as available_count
from EQUIP_VIEW_TABLE
group by state_code, city_code, equipment_type
)
pivot (max(available_count)
for (equipment_type) in
('Sandbag' "CNT_SANDBAG",
'Gabion Basket' "CNT_GABION_BASKET",
'Rapid Deployment Floodwall' "CNT_RAPID_DEPLOYMENT_FLOODWALL",
'Portable Coffer Dam' "CNT_PORTABLE_COFFER_DAM",
'Polyethylene Sheeting' "CNT_POLYETHYLENE_SHEETING",
'Pump' "CNT_PUMP"))
现在,此查询适用于一种计数("可用计数")。数据全部在与州/市相对应的同一行上,没有数据重复,即
STATE CITY SANDBAGS BASKETS FLOODWALL DAM SHEET PUMP
Texas Austin 12 45 11 16 89 8
我需要考虑不同类型的计数。我需要考虑"可用的计数长度"在某些设备上。我尝试使用以下查询完成此操作:
SELECT *
FROM ( SELECT unique state_code, city_code,
equipment_type AS equipment_type_cnt, equipment_type as equipment_type_len,
sum(AVAILABLE_COUNT) AS available_count, SUM(AVAILABLE_COUNT_LENGTH) AS available_count_length
FROM EQUIP_VIEW_TABLE
GROUP BY state_code, city_code, equipment_type )
pivot (MAX(available_count)
FOR (equipment_type_cnt) IN
('Sandbag' "CNT_SANDBAG",
'Polyethylene Sheeting' "CNT_POLYETHYLENE_SHEETING",
'Pump' "CNT_PUMP"))
pivot (MAX(available_count_length)
FOR (equipment_type_len) IN
('Gabion Basket' "CNT_GABION_BASKET",
'Rapid Deployment Floodwall' "CNT_RAPID_DEPLOYMENT_FLOODWALL",
'Portable Coffer Dam' "CNT_PORTABLE_COFFER_DAM"))
我试图基本上添加另一个数据透视部分,我认为它正在工作,但它复制了值并将它们放在不同的行上。结果集看起来像
STATE CITY SANDBAGS SHEET PUMP BASKET FLOODWALL DAM
Texas Austin 12 89 8 16 - -
Texas Austin 12 89 8 - 11 -
Texas Austin 12 89 8 - - 16
它在我的结果集中重复了一行。我需要在同一行上的所有这些值。我一直在尝试不同的想法,但我仍然得到重复的价值观。任何有关这方面的帮助将不胜感激。在此先感谢您的帮助。如果我的问题有点过于复杂或者我没有足够好解释,我会发布更多信息。感谢。
答案 0 :(得分:0)
如果我了解您要执行的操作,我会决定将哪个列用于主查询,并在单个case
中使用sum()
表达式:
SELECT unique state_code, city_code,
equipment_type,
sum(case when equipment_type in ('Gabion Basket',
'Rapid Deployment Floodwall', 'Portable Coffer Dam')
then AVAILABLE_COUNT_LENGTH
else AVAILABLE_COUNT end) AS chosen_count
FROM EQUIP_VIEW_TABLE
GROUP BY state_code, city_code, equipment_type
并保留枢轴原样:
SELECT *
FROM ( SELECT unique state_code, city_code,
equipment_type,
sum(case when equipment_type in ('Gabion Basket',
'Rapid Deployment Floodwall', 'Portable Coffer Dam')
then AVAILABLE_COUNT_LENGTH
else AVAILABLE_COUNT end) AS chosen_count
FROM EQUIP_VIEW_TABLE
GROUP BY state_code, city_code, equipment_type )
pivot (max(chosen_count)
for (equipment_type) in
('Sandbag' "CNT_SANDBAG",
'Gabion Basket' "CNT_GABION_BASKET",
'Rapid Deployment Floodwall' "CNT_RAPID_DEPLOYMENT_FLOODWALL",
'Portable Coffer Dam' "CNT_PORTABLE_COFFER_DAM",
'Polyethylene Sheeting' "CNT_POLYETHYLENE_SHEETING",
'Pump' "CNT_PUMP"))