I'm not very experienced with SPUFI and would like to know how I can get the following query to return in "location" order? It's supposed to total amounts for individual accounts within locations.
select distinct (account) ,location ,SUM(money) from table1 where location = 'WHJ' AND money > 500 group by location, account
This is a basic grouping query which requires only a little surgery to fix. You don't need the DISTINCT because that is a feature of how grouping works.
select location, account , sum(money) from table1 where location = 'WHJ' and money > 500 group by location, account order by location, account
One habit I have is to name the columns in the SELECT list and GROUP BY clause in the same sequence -- this simply makes it easier to verify (see note below) that all non-aggregate columns are included in the GROUP BY.
The other thing to note is that you should always include the ORDER BY if you need to have the results in a particular order. You will often get correctly sorted results without it, if it's the same sequence as the GROUP BY, simply because when the database needs to do a GROUP BY, it has to perform a sort. Nevertheless, it's always a good idea to include the ORDER BY clause if you need a specific order.
Finally, note that you do not really need to GROUP BY or ORDER BY location, since there's only one value in the result set. You can simplify your query to
select 'WHJ', account , sum(money) from table1 where location = 'WHJ' and money > 500 group by account order by account
Use this query if you always run it on one location at a time.
Note: Since you're using SPUFI (a mainframe query interface), you may appreciate the following humour. When I worked on mainframes, we used a special utility to do our syntax verification. It was called IEHIBALL. (Eyeball -- get it?)
For More Information
- What do you think about this answer? E-mail the edtiors at [email protected] with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.