Subject | Re: [firebird-support] Re: Grouping without sorting alphabetically |
---|---|
Author | Venus Software Operations |
Post date | 2015-02-14T14:17:47Z |
I think an additional CTE may be what you want:
WITH cteTestGroups (iGroupSrNo, cTitle, iSubGroupSrNo, cSubGroup AS
(SELECT MIN(A.iSrNo), B.cTitle, MIN(C.iSrNo), C.cSubGroup
FROM sReqSlipTestGroup A
JOIN mTestGroups B ON B.iID = A.iTestGroupID
JOIN lTestGroupsTest C ON C.iPID = B.iID
JOIN mTests D ON D.iID = C.iTestID
WHERE A.iPID = 1
GROUP BY B.lNewPage, A.iSrNo, B.cTitle, C.cSubGroup),
cteOrderGroups(cTitle, cOrder) AS
(select cTitle, min(iGroupSrNo)
from cteTestGroups
group by 1)
SELECT cteTG.*
FROM cteTestGroups cteTG
JOIN cteOrderGroups cteOG on cteTG.cTitle = cteOG.cTitle
ORDER BY cteOG.cOrder, cteTG.iSubGroupSrNo
Maybe things could be simplified further, but this at least ought to work.
Set
Thanks Set for starting me on the right track. Please see my finalized query below which gets me to the expected result.
Kind regards
Bhavbhuti
WITH cteTestGroups AS (
SELECT MIN(sReqSlipTestGroup.iSrNo) AS iGroupSrNo
, MAX(lTestGroupsTest.iSrNo) AS iSubGroupSrNo
, mTestGroups.cTitle
, lTestGroupsTest.cSubGroup
FROM sReqSlipTestGroup sReqSlipTestGroup
JOIN mTestGroups mTestGroups
ON mTestGroups.iID = sReqSlipTestGroup.iTestGroupID
JOIN lTestGroupsTest lTestGroupsTest
ON lTestGroupsTest.iPID = mTestGroups.iID
JOIN mTests mTests
ON mTests.iID = lTestGroupsTest.iTestID
WHERE sReqSlipTestGroup.iPID = 1
GROUP BY mTestGroups.lNewPage
, mTestGroups.cTitle
, lTestGroupsTest.cSubGroup
ORDER BY 1, 2, 3, 4
)
, cteTitleOrder AS (
SELECT MIN(cteTG.iGroupSrNo) AS iTitleOrder
, cteTG.cTitle
FROM cteTestGroups cteTG
GROUP BY cteTG.cTitle
ORDER BY 1
)
, cteFinalOrder AS (
SELECT cteTitleOrder.iTitleOrder
, cteTestGroups.iGroupSrNo
, cteTestGroups.iSubGroupSrNo
, cteTestGroups.cTitle
, cteTestGroups.cSubGroup
FROM cteTestGroups
JOIN cteTitleOrder
ON cteTitleOrder.cTitle = cteTestGroups.cTitle
ORDER BY cteTitleOrder.iTitleOrder
)
SELECT sReqSlipTestGroup.*
, mTestGroups.*
, lTestGroupsTest.*
, mTests.*
FROM sReqSlipTestGroup sReqSlipTestGroup
JOIN mTestGroups mTestGroups
ON mTestGroups.iID = sReqSlipTestGroup.iTestGroupID
JOIN lTestGroupsTest lTestGroupsTest
ON lTestGroupsTest.iPID = mTestGroups.iID
LEFT JOIN cteFinalOrder
ON cteFinalOrder.cTitle = mTestGroups.cTitle
AND cteFinalOrder.cSubGroup = lTestGroupsTest.cSubGroup
JOIN mTests mTests
ON mTests.iID = lTestGroupsTest.iTestID
WHERE sReqSlipTestGroup.iPID = 1
ORDER BY cteFinalOrder.iTitleOrder
, cteFinalOrder.iGroupSrNo
, cteFinalOrder.iSubGroupSrNo
, sReqSlipTestGroup.iSrNo
, lTestGroupsTest.iSrNo