質問

I've got a query which returns parent and child records. Each record will have a total amount field. I'm attempting to sort the query by total amount but on a parent level. The child records will appear immediately below the parent

So for example, if I have the following

| RecordID | Parent   |    Total |

|123       |         1|       90 |

|235       |         0|       70 |

|123       |         0|      100 |

|235       |         1|       60 |

And i sort highest to lowest, it should look like this

RecordID    Parent    Total

| 123           | 1 |          90 |

| 123           | 0 |         100 |

| 235           | 1 |          60 |

| 235           | 0 |          70 |

I'm thinking that I might need to put some sort of sortnumber in the select query for each group, so i this example, RecordID 123 would be assigned 1, and record 235 would be assigned 2.

Using this, I could then Sort by SortNumber, Parent, Total.

Any ideas?

役に立ちましたか?

解決

A simple self JOIN to get the parent value should do it well;

SELECT a.*
FROM mytable a
JOIN mytable b
  ON a.recordid=b.recordid
 AND b.parent=1
ORDER BY b.total,b.recordid,a.parent DESC

An SQLfiddle to test with.

他のヒント

What's wrong with sorting by recordid?

select recordid, parent, total
from yourtable
order by recordid, parent desc, total
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top