Reputation: 1045
I'm trying to split my query results into 2 groups, ones that have a flag of Y and ones that have a flag N. I then need to sort the groups by the based on 2 things.
Here's the query I've tried which doesn't work with the GROUP BY bit:
SELECT location,
country
FROM web_loc_info
WHERE flag = 'Y'
OR flag = 'N'
AND available_online = 'Y'
GROUP BY flag
ORDER BY country,
location_desc
Any help with this would be great so thanks in advance for any replies
Upvotes: 2
Views: 8361
Reputation: 3445
It might be worth clarifying that a "GROUP" in Oracle (from a GROUP BY
operation) is where one or more rows of raw data has been consolidated into a single row in the result.
Recall that:
SELECT flag FROM web_loc_info GROUP BY flag ORDER BY flag
is equivalent to
SELECT DISTINCT flag FROM web_log_info ORDER BY flag
(If the flag column only contains Y and N values, both queries will return 2 rows.)
So, in the future, when you think "group" ask if you mean "summarize the data so that there's one row for each group value" (in this case the "Y"/"N" values in the flag column) in which case the GROUP BY
clause is probably what you're after or if you just want to put sort rows with the same values together in which case you're just looking at ORDER BY
.
I'd say Randy and Harshit above are pretty close only I'd include the FLAG column in the SELECT list so you can see what "group" the LOCATION and COUNTRY values belong to (and making it obvious where the break in the grouping occurs):
SELECT flag,
location,
country
FROM web_loc_info
WHERE flag IN ('Y', 'N')
AND available_online = 'Y'
ORDER BY flag, -- DESC if you want the Y rows to show first
location, -- DESC? or is there actually a column called LOCATION_DESC?
country
Upvotes: 5
Reputation: 560
Can try this
SELECT location, country FROM web_loc_info WHERE flag = 'Y' OR flag = 'N' AND
available_online = 'Y' ORDER BY FLAG,country, location_desc
Upvotes: 2
Reputation: 16673
it doesn't seem like you need the group at all.
SELECT location,
country
FROM web_loc_info
WHERE flag in ( 'Y' , 'N' )
AND available_online = 'Y'
ORDER BY flag desc,
country,
location_desc
Upvotes: 3
Reputation: 116180
All columns you select need to be in your group by, unless you aggregate over them. So in this case, your query would become:
SELECT location,
country
FROM web_loc_info
WHERE flag = 'Y'
OR flag = 'N'
AND available_online = 'Y'
GROUP BY flag,
location,
country,
location_desc
ORDER BY country,
location_desc
location_desc
is needed as well, because you use it in order by
.
Upvotes: 1