Getting a specific SELECT order
Posted in 1991
Topics: SQL Development & Query Writing
Can anyone help? I'm trying to put together an SQL statement which will select a particular set of transactions in a particular order. The table is set up as follows: trans_num (SERIAL) ref_num (INT) trans_date (DATE) description (CHAR) amount (DECIMAL) The two important fields are the trans_num and ref_num. Each transaction has a unique trans_num. The ref_num is used to group together related transactions. It does this by being set as equal to a particular trans_num (sort of like a parent transaction). Here's a list of transaction records (I've left out unnecessary fields): trans_num ref_num 1 2 3 4 2 5 6 7 2 8 9 1 If I do a 'SELECT * FROM trans ORDER BY trans_num' then I get the above order. However, I want to get the record in the order below: trans_num ref_num 1 9 1 <-ref_num equals 1, so this comes after trans_num 1 2 4 2 <-ref_nums equal to, so these must 7 2 <-come immediately after trans_num 2 3 5 6 8 Basically, I want all transactions with the ref_num the same as a particular trans_num, to be grouped together. However, if no ref_num exists, the transactions should be ordered just by their trans_num. Can anyone suggest an efficient SQL SELECT statement which will produce this ordering? Thanks for your help. -- Ben Knox tdc0010@dircon.co.uk ...!ukc!dircon!tdc0010