使用CASE语句问题选择聚合数据

时间:2016-07-21 19:30:25

标签: sql oracle case

我尝试创建查询以获取区域数据,以准备将列移动到另一个表。我们的数据库如何设置是我们有资产和电缆。一个资产可以有很多电缆,但是电缆不能有多个资产。我们目前正在尝试将“区域”字段从“有线”表格(例如下方)移动到“资产”表格。

A_ID    C_ID       Zone        
--------------------------
1       1          Green
1       2          Green   
1       3          Yellow
2       4          Green
2       5          Red
3       6          Yellow
3       7          Yellow
3       8          Yellow
3       9          Red

我希望为资产表设置它的方式是,如果资产包含多个具有不同区域的电缆,如果其中一个区域为黄色,则默认为黄色(例如3条绿色电缆,1条黄色电缆 - Asset_ID有黄区)。接下来,如果它没有任何黄色但至少有1个红色,则默认为红色(例如2条绿色电缆,3条红色电缆 - Asset_ID具有红色区域)。只有它只有绿色区域时才默认为绿色。

使用上面的样本表是我期望的结果。

Expected Results    

A_ID   Zone
-------------
1      Yellow
2      Red
3      Yellow

我尝试使用CASE语句,但我在制定查询时遇到了问题,无法正确分组结果。

非常感谢任何帮助,谢谢你。

3 个答案:

答案 0 :(得分:0)

无需案例或需要陈述。集思考。您需要为优先级分配优先级连接,并首先选择优先级最高的连接。喜欢这个

WITH Priority AS
(
   SELECT * FROM (
   VALUES
     ('Yellow', 1),
     ('Red', 2),
     ('Green', 3)
   ) AS P(Zone,P)
)
SELECT A_ID, Zone
FROM (     
  SELECT A_ID, Zone
         ROW_NUMBER() OVER (PARTITION BY A_ID ORDER BY P.P ASC) AS RN
  FROM AssetTable A
  LEFT JOIN Priority P ON A.Zone = P.Zone
) SUB
WHERE RN = 1 

我不确定我的语法是否适合CTE for Oracle中的VALUES。如果这给出了错误替换为:

WITH Priority AS
(
   SELECT 'Yellow' AS Zone, 1 AS P
     UNION ALL
   SELECT 'Red' AS Zone, 2 AS P
     UNION ALL
   SELECT 'Green' AS Zone, 3 AS P
)

答案 1 :(得分:0)

使用条件聚合和case表达式的一种方法。

select a_id
,case when yellow_count >=1 then 'Yellow'
      when yellow_count = 0 and red_count >=1 then 'Red'
      when yellow_count = 0 and red_count = 0 and green_count >=1 then 'Green'
 end zone
from (select a_id,
      count(case when zone = 'Yellow' then 1 end) yellow_count,
      count(case when zone = 'Red' then 1 end) red_count
      count(case when zone = 'Green' then 1 end) green_count
      from cable_table
      group by a_id) t

答案 2 :(得分:0)

为什么不做一个简单的事情:

SELECT A_ID, MAX( Zone )
FROM table
GROUP BY A_ID

如果某个A_ID有Yellow,则max(区域)返回Yellow
如果某些A_ID没有Yellow,但有Red,那么最大(区域)会返回红色<br> otherwise (no黄色nor红色) max( Zone ) returns绿色

和示例:

with data as (
select 1  a_id,   1 c_id ,         'Green' zone from dual union all
select 1   ,    2  ,        'Green'  from dual union all
select 1 ,      3,          'Yellow' from dual union all
select 2 ,      4 ,         'Green' from dual union all
select 2 ,      5 ,         'Red' from dual union all
select 3  ,     6  ,       'Yellow' from dual union all
select 3   ,    7   ,       'Yellow' from dual union all
select 3   ,    8        ,  'Yellow' from dual union all
select 3   ,    9   ,       'Red' from dual 
)
select a_id, max( zone )
from data
group by a_id


      A_ID MAX(ZO
---------- ------
         1 Yellow
         2 Red   
         3 Yellow
相关问题