Dear Friends,
I have a problem with my TSQL statment.
I need to get previous value for each day and specific unit. Everything goes fine if I have always 2 unit in each day. But if same day has just one unit or less, I cannot have the previous value in the current record.
The Output is this one:
SK_DAYSK_UNITVALUEVALUE_PREVIUS_DAY
201311122
30.00NULL
201311123
34.00NULL
201311132
40.0030.00
201311133
45.0034.00
201311142
50.0040.00
I dont have the second record for 2013-11-14, because in this date I just have value for unit 2.
The final output should include the record:
201311143 045.00
The Statment I have is:
SELECTMAIN.SK_DAY, MAIN.SK_UNIT, SUM(MAIN.VALUE) AS VALUE
,(
SELECT SUM(VND1.VALUE) AS VALUE
FROM FCT_TEST VND1
WHERE CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))>=DATEADD(dd,-1,CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY)))
AND CONVERT(DATE,CONVERT(VARCHAR(10),VND1.SK_DAY))<CONVERT(DATE,CONVERT(VARCHAR(10),MAIN.SK_DAY))
AND VND1.SK_UNIT=MAIN.SK_UNIT
)AS VALUE_PREVIUS_DAY
FROM FCT_TEST MAIN
GROUP BY SK_DAY, MAIN.SK_UNIT
SQL CREATE SCRIPT:
CREATE TABLE [dbo].[FCT_TEST](
[SK_DAY] [int] NOT NULL,
[SK_UNIT] [int] NOT NULL,
[VALUE] [decimal](18, 2) NULL,
CONSTRAINT [PK_FCT_TEST] PRIMARY KEY CLUSTERED
(
[SK_DAY] ASC,
[SK_UNIT] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Thank you!!!
PPSQL