USE [Baza_klienta]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[obliczenie_aktualne_oplaty]
(
@AktualnyPlatnik bigint, @AktualnyRok int
)
RETURNS TABLE
AS
RETURN
(
SELECT [tytul],
[oplata],
[opis],
[decyzja],
[umorzenie_a],
[wymiar],
[wplacone],
[wymiar] - [wplacone] AS [pozostalo]
FROM (
SELECT [fn].[tytul],
[lt].[oplata],
[pt].[opis],
[pt].[decyzja],
[pt].[umorzenie_z],
[pt].[umorzenie_a],
CASE WHEN [fn].[wymiar] IS NULL THEN 0 ELSE [fn].[wymiar] END AS [wymiar],
CASE WHEN [t0].[wplacone] IS NULL THEN 0 ELSE [t0].[wplacone] END AS [wplacone]
FROM [dbo].[fn_wymiar](@AktualnyPlatnik) AS [fn]
INNER JOIN [dbo].[view_lista_tytulow] [lt]
ON [fn].[id_dzialki] = [lt].[id_regionu] AND [fn].[tytul] = [lt].[tytul]
LEFT OUTER JOIN [dbo].[tbl_platnik_tytuly] [pt]
ON [fn].[id_dzialki] = [pt].[id_dzialki] AND [fn].[tytul] = [pt].[tytul]
LEFT OUTER JOIN (
SELECT [id_platnika],
[tytul],
SUM([kwota]) AS [wplacone]
FROM [dbo].[tbl_platnik_wplaty]