SELECT
ROW_NUMBER() over (ORDER BY kh) AS Lp,
kh,
LIMIT,
sum(wartosc) AS kwota,
SUM(kwotarozl) AS kwotarozl,
sum(Przeterminowane) AS Przeterminowane,
sum(P30) AS p30,
isnull(SUM(p60),0) AS p60,
ISNULL(SUM(pp60),0) AS pp60,
ISNULL(SUM(p90),0) AS p90,
case when LIMIT < sum (wartosc) then sum (wartosc) - LIMIT else 0 end AS przekroczony
FROM
(
SELECT
DATA,
termin,
shortcut AS kh,
LimitAmount AS LIMIT,
wartosc,
kwotarozl,
case when termin <= dateadd (day, -1 ,GETDATE()) then wartosc else 0 end AS Przeterminowane,
case when datediff (day, termin, GETDATE()) >0 then case when datediff (day, termin, GETDATE()) <=30 then wartosc else 0 end end AS P30,
case when datediff (day, termin, GETDATE()) >0 then case when datediff (day, termin, GETDATE()) >=31 then case when datediff (day, termin, GETDATE()) <=60 then wartosc else 0 end end end AS P60,
case when datediff (day, termin, GETDATE()) >0 then case when datediff (day, termin, GETDATE()) >=61 then case when datediff (day, termin, GETDATE()) <=90 then wartosc else 0 end end end AS Pp60,
case when datediff (day, termin, GETDATE()) >0 then case when datediff (day, termin, GETDATE()) >90 then wartosc else 0 end end AS P90
FROM PN
INNER JOIN SSCommon.STContractors STC ON pn.khid = stc.Id
WHERE
wartosc > 0
AND typ=0
AND aktywny=1
AND typdk NOT LIKE ('FW')
) AS tt
GROUP BY
kh,
LIMIT