使用group by和Case Statement进行子查询

时间:2017-04-23 23:59:59

标签: sql oracle group-by subquery case

我有两个表,一个是国家/地区表,另一个是阈值表。

国家表包含以下列和数据:

ID Country Count < /强> Year
00001 India 200 2011
00001 India 400 2013
00001 Japan 1000 2011
00001 Japan 550 2013
00001 China 400 2011

阈值表的数据如下:

ID Low Value High Value < /强>
00001 500 1000

这意味着如果Count >= 500然后,如果Count > 500 and < 1000 ,如果Count >= 1000

我想要一个这样的结果:

Country Count Threshold < /强> Low Value High Value
India 600 Medium 500 1000
Japan 1550 High 500 1000
China 400 Low 500 1000

所以我想写一个SQL query

我已经在使用此查询:

SELECT C.Country,C.Count
,CASE WHEN C.Count <= T.Low_Value THEN 'Low' WHEN C.Count BETWEEN T.High_Value AND T.Low_Value THEN 'Medium' ELSE 'High' END AS Threshold,
T.Low_Value, T.High_Value FROM 
(SELECT ID,Country,Sum(Count) AS Count 
FROM Country 
WHERE ID=00001 
GROUP BY ID,Country) C 
JOIN Threshold T 
ON C.ID = T.ID

但是这个查询给出了错误。

任何人都可以建议我如何实现这个目标吗?

  

我正在使用 Oracle

     

错误是 ORA-00979:不是GROUP BY表达式

**This query is just for representation**

2 个答案:

答案 0 :(得分:0)

COUNT是保留字。选择不同的别名或在别名周围使用双引号。

SELECT C.Country,
       C."Count",
       CASE WHEN C."Count" <= T.Low_Value THEN 'Low'
            WHEN C."Count" BETWEEN T.High_Value AND T.Low_Value THEN 'Medium'
            ELSE 'High' END AS Threshold,
       T.Low_Value,
       T.High_Value
FROM   (
  SELECT ID,Country,Sum("Count") AS "Count"
  FROM Country 
  WHERE ID=00001 
  GROUP BY ID,Country
) C 
JOIN Threshold T 
ON C.ID = T.ID

答案 1 :(得分:0)

可以使用以下方法完成:

SELECT Country
      ,Total
      ,CASE WHEN Total <= Low_Value THEN 'Low'
            WHEN Total BETWEEN Low_Value AND High_Value THEN 'Medium'
        ELSE 'High' END AS Threshold
      FROM (SELECT ID
          ,Country
          ,Low_Value
          ,High_Value
          ,SUM(Count) Total
         FROM (SELECT C.ID
             ,C.Country
             ,C.Count
             ,T.Low_Value
             ,T.High_Value
           FROM Country C JOIN Threshold T
           ON C.ID=T.ID
           WHERE C.ID =00001)
        GROUP BY Country,Low_Value,High_Value)