首先我可以事先道歉,因为我知道有很多问题和答案,但我根本无法理解它!
我有一个表格,其中包含客户参考号[MT-CODE]
,发票参考号[REFERENCE]
和日期[POST-DATE]
,我可以使用DATEDIFF
来查看是否账单已逾期。
列[MT-CODE]
和[REFERENCE]
不是唯一的,因此当我想查看是否有任何发票过期时,我可以使用分组,我认为每{{1}行需要一行}。
我目前的查询如下:
[REFERENCE]
目前返回2行:
SELECT
nt.[MT-CODE], nt.[REFERENCE],
DATEDIFF(day, nt.[POST-DATE], GETDATE()) AS LateDays
FROM
pub1_nomtrans nt
WHERE
([UNDONE-FLAG] = 0)
AND ([POST-TYPE] = N'BC')
AND ([CONTRA-CODE] = N'X20')
AND (ISNULL([BILLED-PAID-FLAG], N'') <> 'C')
AND [Reference] = '1800509'
GROUP BY
nt.[MT-CODE], nt.[REFERENCE], nt.[POST-DATE]
我想做的是自己进行连接,以便获得每行的最大延迟天数 - 即此查询的输出应为:
MT-CODE REFERENCE LateDays
----------------------------
012790/0033 1800509 93
012790/0033 1800509 89
感激地收到任何指示。
谢谢
答案 0 :(得分:0)
嗯,你当前的查询中并不真正需要group by,而且你真的不需要自我加入。您可以将当前查询用作派生表,并按其结果执行分组:
SELECT [MT-CODE], [REFERENCE], MAX(LateDays)
FROM
(
SELECT nt.[MT-CODE], nt.[REFERENCE], DATEDIFF(day, nt.[POST-DATE], GETDATE()) AS LateDays
from pub1_nomtrans nt
WHERE ([UNDONE-FLAG] = 0) AND ([POST-TYPE] = N'BC') AND ([CONTRA-CODE] = N'X20') AND (ISNULL([BILLED-PAID-FLAG], N'') <> 'C')
AND [Reference]='1800509'
) x
GROUP BY [MT-CODE], [REFERENCE]
答案 1 :(得分:0)
有很多方法可以实现这一目标。
如果我们假设您每次只获得1条记录,则可以使用offset / top和order by。 row_number / cross适用于多次返回,但每条记录需要前N个。
我没有给出交叉应用示例,但它基本上表示对于基本集中的每一行,从第二组返回N行,我们可以使N成为顶行并按LateDays排序;从而获得每条记录的最新日期数据。
SELECT TOP 1
nt.[MT-CODE], nt.[REFERENCE],
DATEDIFF(day, nt.[POST-DATE], GETDATE()) AS LateDays
FROM
pub1_nomtrans nt
WHERE
([UNDONE-FLAG] = 0)
AND ([POST-TYPE] = N'BC')
AND ([CONTRA-CODE] = N'X20')
AND (ISNULL([BILLED-PAID-FLAG], N'') <> 'C')
AND [Reference] = '1800509'
GROUP BY
nt.[MT-CODE], nt.[REFERENCE], nt.[POST-DATE]
ORDER BY LateDays DESC
或
SELECT
nt.[MT-CODE], nt.[REFERENCE],
DATEDIFF(day, nt.[POST-DATE], GETDATE()) AS LateDays
FROM
pub1_nomtrans nt
WHERE
([UNDONE-FLAG] = 0)
AND ([POST-TYPE] = N'BC')
AND ([CONTRA-CODE] = N'X20')
AND (ISNULL([BILLED-PAID-FLAG], N'') <> 'C')
AND [Reference] = '1800509'
GROUP BY
nt.[MT-CODE], nt.[REFERENCE], nt.[POST-DATE]
ORDER BY LateDays DESC
FETCH NEXT 1
或者 - 如果多个记录返回不同的mt /参考值,并且您希望每个记录的最大延迟天数。
WITH CTE AS (
SELECT
nt.[MT-CODE], nt.[REFERENCE],
DATEDIFF(day, nt.[POST-DATE], GETDATE()) AS LateDays
row_number() over (partition by nt.[MT-CODE], nt.[REFERENCE] order by DATEDIFF(day, nt.[POST-DATE], GETDATE() DESC) as RN
FROM
pub1_nomtrans nt
WHERE
([UNDONE-FLAG] = 0)
AND ([POST-TYPE] = N'BC')
AND ([CONTRA-CODE] = N'X20')
AND (ISNULL([BILLED-PAID-FLAG], N'') <> 'C')
AND [Reference] = '1800509'
GROUP BY
nt.[MT-CODE], nt.[REFERENCE], nt.[POST-DATE])
SELECT * FROM CTE WHERE RN = 1