简体   繁体   中英

Sub-Query with group by and Case Statement

I have two tables , one is Country table and another one is Threshold Table.

Country table has columns and data like this :

ID Country Count Year
00001 India 200 2011
00001 India 400 2013
00001 Japan 1000 2011
00001 Japan 550 2013
00001 China 400 2011

And the Threshold table has data like this :

ID Low Value High Value
00001 500 1000

That means if the Count >= 500 then Low , if the Count > 500 and < 1000 the Medium and if Count >= 1000 then High .

I want a result like this :

Country Count Threshold Low Value High Value
India 600 Medium 500 1000
Japan 1550 High 500 1000
China 400 Low 500 1000

So I want to write a SQL query .

I am already using this 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

But this query is giving error.

Can anyone one please suggest me how to implement this ?

I am using Oracle

The error is ORA-00979 : not a GROUP BY expression

**This query is just for representation**

COUNT is a reserved word. Either pick a different alias or use double quotes around the alias.

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

It can be done by using this :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM