嵌套SQL和带有WHERE CLAUSE ISSUE的计算字段

时间:2015-05-21 02:15:28

标签: sql oracle11g where average

我正在尝试进行以下查询:

SELECT m.name,s.category,
'$' || cast((select avg(retail) from STOCK
              INNER JOIN MANUFACTURER
              ON STOCK.DEALERID=MANUFACTURER.DEALERID
               WHERE s.category='sedan' or s.category='suv') 
               as decimal(4,2)) as AVG_RRP 
 from manufacturer m 
      join stock s 
      using (DEALERID)
       WHERE (select(sum(retail) from stock)/
              (select count(distinct category) from manufacturer)) >5000

需要输出:

  • 我想显示制造商名称和库存类别
  • 我想生成一个计算字段,我发现HONDA和GM的平均零售价格格式为$ XX.XX
  • 我还要列出所有类别的平均零售价格超过5000

表格格式:

MANFACTURER: DEALERID#,name,phone,state
STOCK: VIN#,name,pudate,dealerid,cost,retail,sdiscount,category

期望的输出:

Manufactuer Name - Stock Category - (Calculated Field)
Honda              Sedan            $XX.XX

我正在使用oracle 11g isql

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

如果我的理解是正确的......这就是你需要实现的目标

  1. 需要显示轿车和suv的平均零售价
  2. 需要显示除轿车和SUV以外的其他类别的平均零售价格 总和(库存)/计数(类别)> 5000
  3. 希望以下代码可以帮助您

    select m.name,
           s.category,
           avg(retail) 
     from STOCK s ,
          MANUFACTURER m 
    where 
         STOCK.DEALERID=MANUFACTURER.DEALERID 
         and (s.category='sedan' or s.category='suv') 
    Group by m.name,s.cateogry 
    
    Union 
    
    select m.name,
           s.category,
           avg(retail) 
    from STOCK s ,
         MANUFACTURER m 
    where 
       STOCK.DEALERID=MANUFACTURER.DEALERID 
    AND (select(sum(retail) from 
                stock s ,manufacturer m 
                where STOCK.DEALERID=MANUFACTURER.DEALERID 
                and (s.category !='sedan' or s.category !='suv') 
          )/ 
           select count(distinct category) 
              from stock s ,manufacturer m 
               where STOCK.DEALERID=MANUFACTURER.DEALERID 
               and (s.category !='sedan' or s.category !='suv') )) >5000 
    Group by m.name,s.cateogry
    

    您可以根据自己的意愿提供$符号和roundings

    可以有更好的方法..但是我很快就会想到这个......并检查