遵循上一个question
我有这个问题:
SELECT Acc.DocTLItem.TLRef ,
Acc.DocTLItem.Debit AS deb,
Acc.DocTLItem.Credit AS cred,
info.MiladiToShamsi(Acc.DocTLItem.StartDocDate) Date,
Acc.TL.TLCode ,
Acc.DocTLItem.DocTLHeaderRef ,
Acc.DocTLHeader.Num
FROM Acc.DocTLItem
INNER JOIN Acc.TL ON Acc.DocTLItem.TLRef = Acc.TL.Id
INNER JOIN Acc.DocTLHeader ON Acc.DocTLItem.DocTLHeaderRef = Acc.DocTLHeader.Id
ORDER BY ( CASE WHEN debit > 0 THEN 0 ELSE 1 END ) ,
Acc.TL.TLCode ,
debit
结果:
TLRef deb cred Date TLCode DocTLHeaderRef Num
--------------------------------------------------------------------------
44 1 0 1396/09/12 111 16 2
44 1 0 1396/09/21 111 18 4
28 13 0 1396/09/11 982 15 1
28 10 0 1396/09/19 982 17 3
44 0 10 1396/09/19 111 17 3
44 0 1 1396/09/21 111 18 4
44 0 9 1396/09/11 111 15 1
44 0 1 1396/09/12 111 16 2
如何按日期分组,然后按日期排序?
我需要生成一个这样的结果集,债务首先出现,然后在所有按日期分组后由TLCode列排序。
预期结果:
TLRef deb cred Date TLCode DocTLHeaderRef Num
--------------------------------------------------------------------------------
44 1 0 1396/09/12 111 16 2
28 13 0 1396/09/11 982 15 1
28 10 0 1396/09/19 982 17 3
44 0 9 1396/09/11 111 15 1
44 0 1 1396/09/12 111 16 2
44 0 10 1396/09/19 111 17 3
Sum 24 20
44 1 0 1396/09/21 111 18 4
44 0 1 1396/09/21 111 18 4
Sum 1 1
答案 0 :(得分:1)
可能是以下查询块可以帮助您: 此查询将分四步进行:
if
答案 1 :(得分:0)
您可以尝试进行排序。
;WITH CTE AS (
SELECT Acc.DocTLItem.TLRef ,
Acc.DocTLItem.Debit AS deb,
Acc.DocTLItem.Credit AS cred,
info.MiladiToShamsi(Acc.DocTLItem.StartDocDate) Date,
Acc.TL.TLCode ,
Acc.DocTLItem.DocTLHeaderRef ,
Acc.DocTLHeader.Num,
ROW_NUMBER() OVER(PARTITION BY Acc.DocTLItem.Debi, Acc.DocTLItem.Credit, Acc.TL.TLCode ORDER BY Acc.DocTLItem.StartDocDate ) AS RN
FROM Acc.DocTLItem
INNER JOIN Acc.TL ON Acc.DocTLItem.TLRef = Acc.TL.Id
INNER JOIN Acc.DocTLHeader ON Acc.DocTLItem.DocTLHeaderRef = Acc.DocTLHeader.Id
)
SELECT * FROM CTE
ORDER BY
RN,
( CASE WHEN deb > 0 THEN 0 ELSE 1 END ) ,
TLCode ,
[Date],
deb