Group by does not work - SQL 2008 R2 - sql-server
I have 3 rows that I need to be outputted into just 1 row, the script below should do, but I can't seem to have the expected result, it always shows up as 3 rows, is there something I'm missing? should I sum all the fields since they are all in the "GROUP" clause?
Btw, its working just before I made changes to the following result fields;
TSL_DAY_A
TSL_NET_A
TSL_TX_SAL
TSL_CHG
These fields were initially assigned with 0.00 as default values.
I have my eyes already tired staring at it,...
SELECT BR_CODE
,N_CHECK
,CLAS_C
,CLAS_TRD_C
,STOR_NO
,SUM(TSL_NEW_A) AS TSL_NEW_A
,SUM(TSL_OLD_A) AS TSL_OLD_A
,SalesType
,SUM(TSL_DAY_A) AS TSL_DAY_A
,SUM(TSL_DIS_A) AS TSL_DIS_A
,TSL_DIS_B
,SUM(TSL_DIS_C) AS TSL_DIS_C
,TSL_DIS_D
,SUM(TSL_DIS_E) AS TSL_DIS_E
,TSL_Dis_F
,TSL_Dis_G
,TSL_Dis_H
,TSL_Dis_I
,TSL_Dis_J
,TSL_Dis_K
,TSL_Dis_L
,SUM(TSL_TAX_A) AS TSL_TAX_A
,TSL_TAX_B
,TSL_ADJ_A
,TSL_ADJ_POS
,TS_ADJ_NEG
,TSL_ADJ_NT_POS
,TSL_ADJ_NT_NEG
,SUM(TSL_NET_A) AS TSL_NET_A
,SUM(TSL_VOID) AS TSL_VOID
,SUM(TSL_RFND) AS TSL_RFND
,SUM(TSL_TX_SAL) AS TSL_TX_SAL
,SUM(TSL_NX_SAL) AS TSL_NX_SAL
,TSL_CHG
,SUM(TSL_CSH) AS TSL_CSH
,SUM(TSL_GC) AS TSL_GC
,TSL_EPS
,TSL_TND
,TSL_MCRD
,TSL_VISA
,TSL_AMEX
,TSL_DINERS
,TSL_JBC
,TSL_OTCRD
,TSL_SV_CHG
,TSL_OT_CHG
,SUM(TSL_FT) AS TSL_FT
,SUM(TSL_LT) AS TSL_LT
,SUM(TSL_NT) AS TSL_NT
,SUM(TSL_BEG_INV) AS TSL_BEG_INV
,SUM(TSL_END_INV) AS TSL_END_INV
,SUM(TSL_TC_CASH) AS TSL_TC_CASH
,SUM(TSL_TC_GC) AS TSL_TC_GC
,TSL_TC_EPS
,TSL_TC_TND
,TSL_TC_MCD
,TSL_TC_VIS
,TSL_TC_AMX
,TSL_TC_DIN
,TSL_TC_JBC
,TSL_TC_OC
,TSL_MCH
,TSL_SRL
,SUM(TSL_ZCNT) AS TSL_ZCNT
,TSL_TIME
,TSL_DTE
FROM(
SELECT
BR_CODE
,N_CHECK
,CLAS_C
,CLAS_TRD_C
,STOR_NO
,SUM(TSL_NEW_A) AS TSL_NEW_A
,SUM(TSL_OLD_A) AS TSL_OLD_A
,SalesType
,SUM(TSL_DAY_A) AS TSL_DAY_A
,SUM(TSL_DIS_A) AS TSL_DIS_A
,TSL_DIS_B
,SUM(TSL_DIS_C) AS TSL_DIS_C
,TSL_DIS_D
,SUM(TSL_DIS_E) AS TSL_DIS_E
,TSL_Dis_F
,TSL_Dis_G
,TSL_Dis_H
,TSL_Dis_I
,TSL_Dis_J
,TSL_Dis_K
,TSL_Dis_L
,SUM(TSL_TAX_A) AS TSL_TAX_A
,TSL_TAX_B
,TSL_ADJ_A
,TSL_ADJ_POS
,TS_ADJ_NEG
,TSL_ADJ_NT_POS
,TSL_ADJ_NT_NEG
,SUM(TSL_NET_A) AS TSL_NET_A
,SUM(TSL_VOID) AS TSL_VOID
,SUM(TSL_RFND) AS TSL_RFND
,SUM(TSL_TX_SAL) AS TSL_TX_SAL
,SUM(TSL_NX_SAL) AS TSL_NX_SAL
,TSL_CHG
,SUM(TSL_CSH) AS TSL_CSH
,SUM(TSL_GC) AS TSL_GC
,TSL_EPS
,TSL_TND
,TSL_MCRD
,TSL_VISA
,TSL_AMEX
,TSL_DINERS
,TSL_JBC
,TSL_OTCRD
,TSL_SV_CHG
,TSL_OT_CHG
,SUM(TSL_FT) AS TSL_FT
,SUM(TSL_LT) AS TSL_LT
,SUM(TSL_NT) AS TSL_NT
,SUM(TSL_BEG_INV) AS TSL_BEG_INV
,SUM(TSL_END_INV) AS TSL_END_INV
,SUM(TSL_TC_CASH) AS TSL_TC_CASH
,SUM(TSL_TC_GC) AS TSL_TC_GC
,TSL_TC_EPS
,TSL_TC_TND
,TSL_TC_MCD
,TSL_TC_VIS
,TSL_TC_AMX
,TSL_TC_DIN
,TSL_TC_JBC
,TSL_TC_OC
,TSL_MCH
,TSL_SRL
,SUM(TSL_ZCNT) AS TSL_ZCNT
,TSL_TIME
,TSL_DTE
FROM
(SELECT
#branchcode AS BR_CODE
,#ncheck AS N_CHECK
,#classc AS CLAS_C
,#classtrd AS CLAS_TRD_C
,#storeno AS STOR_NO
,SUM(CAST(NGTOTAL AS DECIMAL(16,2)) + CAST(OGTOTAL AS DECIMAL(16,2))) AS TSL_NEW_A
,SUM(CAST(OGTOTAL AS DECIMAL(16,2))) AS TSL_OLD_A
,#salestype AS SalesType
,SUM(((CAST(SALESREGULAR AS DECIMAL(16,2)) - CAST(SALESVATEXEMPT AS DECIMAL(16,2))) +
CAST(SALESCD20 AS DECIMAL(16,2)) +
CAST(SALESCD5 AS DECIMAL(16,2)) +
CAST(SALEPWD AS DECIMAL(16,2)) +
CAST(SALESTGOVT AS DECIMAL(16,2)) +
CAST(SALESZERORATED AS DECIMAL(16,2)) +
CAST(DISCREGULARAMT AS DECIMAL(16,2)) +
CAST(DISCSCD20AMT AS DECIMAL(16,2)) +
CAST(DISCSCD5AMT AS DECIMAL(16,2)) +
CAST(DISCPWD20AMT AS DECIMAL(16,2)) +
CAST(DISCPWD5AMT AS DECIMAL(16,2)) +
CAST(VOIDTRANAMT AS DECIMAL(16,2)) +
CAST(ITEMVOIDAMT AS DECIMAL(16,2)) +
CAST(TICKETRETAMT AS DECIMAL(16,2)) +
CAST(ITEMRETAMT AS DECIMAL(16,2)))/1.12) + CAST(SALESVATEXEMPT AS DECIMAL(16,2)) AS TSL_DAY_A --SUM(cast(round((cast(TSALES as decimal)/1.12),2) AS DECIMAL(16,2))) AS TSL_DAY_A --Help
,SUM(ABS(CAST(DISCREGULARAMT AS DECIMAL(16,2)))) AS TSL_DIS_A
,0.00 AS TSL_DIS_B
,SUM(CAST(DISCSCD20AMT AS DECIMAL(16,2)) + CAST(DISCSCD5AMT AS DECIMAL(16,2))) AS TSL_DIS_C
,0.00 AS TSL_DIS_D
,SUM(CAST(DISCSCD20AMT AS DECIMAL(16,2)) + CAST(DISCSCD5AMT AS DECIMAL(16,2))) AS TSL_DIS_E
,0.00 AS TSL_Dis_F
,0.00 AS TSL_Dis_G
,0.00 AS TSL_Dis_H
,0.00 AS TSL_Dis_I
,0.00 AS TSL_Dis_J
,0.00 AS TSL_Dis_K
,0.00 AS TSL_Dis_L
,SUM(CAST(VATSALEAMT AS DECIMAL(16,2))) AS TSL_TAX_A
,0.00 AS TSL_TAX_B
,0.00 TSL_ADJ_A
,0.00 AS TSL_ADJ_POS
,0.00 AS TS_ADJ_NEG
,0.00 AS TSL_ADJ_NT_POS
,0.00 AS TSL_ADJ_NT_NEG
,SUM(CAST(DGROSSSALES AS DECIMAL(16,2)) - CAST(TOTALTAXVALUE AS DECIMAL(16,2))) AS TSL_NET_A --Help
,SUM(CAST(VOIDTRANAMT AS DECIMAL(16,2))) AS TSL_VOID
,SUM(ABS(CAST(ITEMRETAMT AS DECIMAL(16,2)))) AS TSL_RFND
,SUM(((CAST(SALESREGULAR AS DECIMAL(16,2)) + CAST(SALESVATEXEMPT AS DECIMAL(16,2))) +
CAST(SALESCD20 AS DECIMAL(16,2)) +
CAST(SALESCD5 AS DECIMAL(16,2)) +
CAST(SALEPWD AS DECIMAL(16,2)) +
CAST(SALESTGOVT AS DECIMAL(16,2)) +
CAST(SALESZERORATED AS DECIMAL(16,2)) +
CAST(DISCREGULARAMT AS DECIMAL(16,2)) +
CAST(DISCSCD20AMT AS DECIMAL(16,2)) +
CAST(DISCSCD5AMT AS DECIMAL(16,2)) +
CAST(DISCPWD20AMT AS DECIMAL(16,2)) +
CAST(DISCPWD5AMT AS DECIMAL(16,2)) +
CAST(VOIDTRANAMT AS DECIMAL(16,2)) +
CAST(ITEMVOIDAMT AS DECIMAL(16,2)) +
CAST(TICKETRETAMT AS DECIMAL(16,2)) +
CAST(ITEMRETAMT AS DECIMAL(16,2)))) AS TSL_TX_SAL --Help
,(CAST(SALESVATEXEMPT AS DECIMAL(16,2)) + (CAST(ZERORATEDSALEAMT AS DECIMAL(16,2)) - CAST(ZERORATEDSALETAXVALUE AS DECIMAL(16,2)))) AS TSL_NX_SAL
,SUM(CAST(CCARDATMCHRGONLINEAMT AS DECIMAL(16,2))) AS TSL_CHG --Help
,SUM(CAST(TENDERCASHAMT AS DECIMAL(16,2))) AS TSL_CSH
,SUM(CAST(OTHTENDERSMGCAMT AS DECIMAL(16,2)) + CAST(OTHTENDERSODEXOAMT AS DECIMAL(16,2))) AS TSL_GC --+ CAST(TENDERCHKAMT AS DECIMAL) AS TSL_GC
,0.00 AS TSL_EPS
,0.00 AS TSL_TND
,0.00 AS TSL_MCRD
,0.00 AS TSL_VISA
,0.00 AS TSL_AMEX
,0.00 AS TSL_DINERS
,0.00 AS TSL_JBC
,0.00 AS TSL_OTCRD
,0.00 AS TSL_SV_CHG
,0.00 AS TSL_OT_CHG
,SUM(CAST(ABS(BEGSI) AS INT)) AS TSL_FT
,SUM(CAST(ABS(LASSI) AS INT)) AS TSL_LT
,SUM(CAST((CAST(QTYREGULAR AS DECIMAL(18,2)) + CAST(QTYSCD20 AS DECIMAL(18,2)) + CAST(QTYSCD5 AS DECIMAL(18,2)) + CAST(QTYPWD AS DECIMAL(18,2)) + CAST(QTYTGOVT AS DECIMAL(18,2)) + CAST(QTYZERORATED AS DECIMAL(18,2))
+ CAST(QTYVATEXEMPT AS DECIMAL(18,2)) + CAST(DISCREGULARQTY AS DECIMAL(18,2)) + CAST(DISCSCD20QTY AS DECIMAL(18,2)) + CAST(DISCSCD5QTY AS DECIMAL(18,2)) + CAST(DISCPWD20QTY AS DECIMAL(18,2))
+ CAST(DISCPWD5QTY AS DECIMAL(18,2)) + CAST(VOIDTRANQTY AS DECIMAL(18,2)) + CAST(ITEMVOIDQTY AS DECIMAL(18,2))*-1 + CAST(TICKETRETQTY AS DECIMAL(18,2))*-1 + CAST(ITEMRETQTY AS DECIMAL(18,2))*-1
+ CAST(ADDLOANTOTQTY AS DECIMAL(18,2))) AS INT)) AS TSL_NT
,SUM(CAST(ABS(BEGSI) AS INT)) AS TSL_BEG_INV
,SUM(CAST(ABS(LASSI) AS INT)) AS TSL_END_INV
,SUM(CAST(QTYREGULAR AS INT)) as TSL_TC_CASH
,SUM(CAST(OTHTENDERSMGCQTY AS INT) + CAST(OTHTENDERSODEXOQTY AS INT)) AS TSL_TC_GC --+ CAST(TENDERCHKQTY AS INT) AS TSL_TC_GC
,0 AS TSL_TC_EPS
,0 AS TSL_TC_TND
,0 AS TSL_TC_MCD
,0 AS TSL_TC_VIS
,0 AS TSL_TC_AMX
,0 AS TSL_TC_DIN
,0 AS TSL_TC_JBC
,0 AS TSL_TC_OC
,#machineno AS TSL_MCH
,0 AS TSL_SRL
,SUM(CAST(ABS(ZCOUNTER) AS INT)) AS TSL_ZCNT
--,LEFT(CONVERT(TIME,GETDATE()),8) AS TSL_TIME
,RIGHT('00'+RTRIM(CAST(DATEPART(HH,GETDATE())AS VARCHAR(5))),2)+RIGHT('00'+RTRIM(CAST(DATEPART(MI,GETDATE()) AS VARCHAR(5))),2)+RIGHT('00'+RTRIM(CAST(DATEPART(SS,GETDATE()) AS VARCHAR(5))),2) AS TSL_TIME
--,SUBSTRING(convert(varchar,WorkDate,111),6,2)+'/'+Right(convert(varchar,WorkDate,111),2)+'/'+left(convert(varchar,WorkDate,111),4) AS TSL_DTE
,SUBSTRING(convert(varchar,WorkDate,111),6,2)+Right(convert(varchar,WorkDate,111),2)+left(convert(varchar,WorkDate,111),4) AS TSL_DTE
FROM dbo.TermZTran t
LEFT JOIN
(SELECT sLessee, sTenantNumber AS TenantCode, sStoreNumber FROM mLandlordStore) tInfo
ON CAST(t.STORE AS INT) = CAST(tInfo.sStoreNumber AS INT)
WHERE CAST(t.Store AS INT) = CAST(#branchcode AS INT)
--AND CAST(t.POS AS int) = CAST(#posno AS int)
AND tInfo.sLessee = #lesseeCode
AND CONVERT(nvarchar(10),t.WorkDate,101) = #trandate
--AND CONVERT(nvarchar(10),t.WorkDate,101) = '04/16/2013' --#trandate
GROUP BY
SALESVATEXEMPT
,ZERORATEDSALEAMT
,ZERORATEDSALETAXVALUE
,WorkDate
) tFinal
--WHERE CAST(BR_CODE AS INT) = CAST('0040' AS INT)
GROUP BY
BR_CODE
,N_CHECK
,CLAS_C
,CLAS_TRD_C
,STOR_NO
,TSL_NEW_A
,TSL_OLD_A
,SalesType
,TSL_DAY_A
,TSL_DIS_A
,TSL_DIS_B
,TSL_DIS_C
,TSL_DIS_D
,TSL_DIS_E
,TSL_Dis_F
,TSL_Dis_G
,TSL_Dis_H
,TSL_Dis_I
,TSL_Dis_J
,TSL_Dis_K
,TSL_Dis_L
,TSL_TAX_A
,TSL_TAX_B
,TSL_ADJ_A
,TSL_ADJ_POS
,TS_ADJ_NEG
,TSL_ADJ_NT_POS
,TSL_ADJ_NT_NEG
,TSL_NET_A
,TSL_VOID
,TSL_RFND
,TSL_TX_SAL
,TSL_NX_SAL
,TSL_CHG
,TSL_CSH
,TSL_GC
,TSL_EPS
,TSL_TND
,TSL_MCRD
,TSL_VISA
,TSL_AMEX
,TSL_DINERS
,TSL_JBC
,TSL_OTCRD
,TSL_SV_CHG
,TSL_OT_CHG
,TSL_FT
,TSL_LT
,TSL_NT
,TSL_BEG_INV
,TSL_END_INV
,TSL_TC_CASH
,TSL_TC_GC
,TSL_TC_EPS
,TSL_TC_TND
,TSL_TC_MCD
,TSL_TC_VIS
,TSL_TC_AMX
,TSL_TC_DIN
,TSL_TC_JBC
,TSL_TC_OC
,TSL_MCH
,TSL_SRL
,TSL_ZCNT
,TSL_TIME
,TSL_DTE) dt
GROUP BY
dt.BR_CODE
,dt.CLAS_C
,dt.CLAS_TRD_C
,dt.N_CHECK
,dt.STOR_NO
,dt.SalesType
,TSL_DAY_A
,TSL_DIS_A
,TSL_DIS_B
,TSL_DIS_C
,TSL_DIS_D
,TSL_DIS_E
,TSL_Dis_F
,TSL_Dis_G
,TSL_Dis_H
,TSL_Dis_I
,TSL_Dis_J
,TSL_Dis_K
,TSL_Dis_L
,TSL_TAX_A
,TSL_TAX_B
,TSL_ADJ_A
,TSL_ADJ_POS
,TS_ADJ_NEG
,TSL_ADJ_NT_POS
,TSL_ADJ_NT_NEG
,TSL_NET_A
,TSL_VOID
,TSL_RFND
,TSL_TX_SAL
,TSL_NX_SAL
,TSL_CHG
,TSL_CSH
,TSL_GC
,TSL_EPS
,TSL_TND
,TSL_MCRD
,TSL_VISA
,TSL_AMEX
,TSL_DINERS
,TSL_JBC
,TSL_OTCRD
,TSL_SV_CHG
,TSL_OT_CHG
,TSL_FT
,TSL_LT
,TSL_NT
,TSL_BEG_INV
,TSL_END_INV
,TSL_TC_CASH
,TSL_TC_GC
,TSL_TC_EPS
,TSL_TC_TND
,TSL_TC_MCD
,TSL_TC_VIS
,TSL_TC_AMX
,TSL_TC_DIN
,TSL_TC_JBC
,TSL_TC_OC
,TSL_MCH
,TSL_SRL
,TSL_ZCNT
,TSL_TIME
,TSL_DTE
Here's a script to create the sample tables and data
USE [LandLord]
GO
/****** Object: Table [dbo].[mLandlordStore] Script Date: 04/25/2013 20:21:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[mLandlordStore](
[IDNumber] [int] IDENTITY(1,1) NOT NULL,
[sStoreNumber] [nvarchar](50) NOT NULL,
[sLessee] [nvarchar](50) NOT NULL,
[sLesseeNumber] [int] NOT NULL,
[sHOGenerated] [varchar](1) NOT NULL,
[LastTranNo] [int] NULL,
[sSpace] [nvarchar](50) NULL,
[sMallCode] [nvarchar](20) NULL,
[sTenantNumber] [nvarchar](20) NULL,
[sClassCode] [nvarchar](20) NULL,
[sTradeCode] [nvarchar](20) NULL,
[sOutletNumber] [nvarchar](20) NULL,
[nSaleType] [int] NULL,
[BatchCount] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[mLandlordStore] ON
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (1, N'40', N'SMCOIN', 11002558, N'Y', 0, N'01', N'72', N'011002559', N'01', N'SAP', N'03', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (3, N'1033', N'SMCOIN', 103312345, N'Y', 0, N'01', N'73', N'7312345', N'01', N'SAP', N'04', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (4, N'1133', N'ACI', 113312345, N'Y', 0, N'01', N'74', N'7412345', N'01', N'SAP', N'05', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (5, N'1233', N'ALI', 123312345, N'Y', 0, N'01', N'75', N'7512345', N'01', N'SAP', N'06', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (6, N'1333', N'MWC', 133312345, N'Y', 0, N'01', N'76', N'7612345', N'01', N'SAP', N'07', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (7, N'1433', N'OCLP', 143312345, N'Y', 0, N'01', N'77', N'7712345', N'01', N'SAP', N'08', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (8, N'1533', N'RLC', 153312345, N'Y', 0, N'01', N'78', N'7812345', N'01', N'SAP', N'09', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (9, N'1633', N'SLE', 163312345, N'Y', 0, N'01', N'79', N'7912345', N'01', N'SAP', N'10', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (10, N'1733', N'STAR', 173312345, N'Y', 0, N'01', N'80', N'8012345', N'01', N'SAP', N'11', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (11, N'1833', N'WM', 183312345, N'Y', 0, N'01', N'81', N'8112345', N'01', N'SAP', N'12', 1, 0)
INSERT [dbo].[mLandlordStore] ([IDNumber], [sStoreNumber], [sLessee], [sLesseeNumber], [sHOGenerated], [LastTranNo], [sSpace], [sMallCode], [sTenantNumber], [sClassCode], [sTradeCode], [sOutletNumber], [nSaleType], [BatchCount]) VALUES (12, N'1933', N'FSI', 193312345, N'Y', 0, N'01', N'82', N'8212345', N'01', N'SAP', N'13', 1, 0)
SET IDENTITY_INSERT [dbo].[mLandlordStore] OFF
/****** Object: Default [DF_mLandlordStore_LastTranNo] Script Date: 04/25/2013 20:21:42 ******/
ALTER TABLE [dbo].[mLandlordStore] ADD CONSTRAINT [DF_mLandlordStore_LastTranNo] DEFAULT ((1)) FOR [LastTranNo]
GO
USE [LandLord]
GO
/****** Object: Table [dbo].[TermZTran] Script Date: 04/25/2013 20:19:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TermZTran](
[HeaderID] [uniqueidentifier] NOT NULL,
[WorkDate] [smalldatetime] NOT NULL,
[ProcessDate] [smalldatetime] NOT NULL,
[ProcessMode] [nvarchar](10) NOT NULL,
[POSCount] [int] NULL,
[SalePharma] [money] NULL,
[SaleNonPharma] [money] NULL,
[VoidAmount] [money] NULL,
[VoidCount] [int] NULL,
[ZCOUNTER] [nvarchar](4000) NULL,
[STORE] [nvarchar](4000) NULL,
[POS] [nvarchar](4000) NULL,
[DATE] [nvarchar](300) NULL,
[TIME] [nvarchar](300) NULL,
[OGTOTAL] [nvarchar](300) NULL,
[NGTOTAL] [nvarchar](300) NULL,
[BEGSI] [nvarchar](300) NULL,
[LASSI] [nvarchar](300) NULL,
[TSALES] [nvarchar](300) NULL,
[QTYREGULAR] [nvarchar](300) NULL,
[SALESREGULAR] [nvarchar](300) NULL,
[QTYSCD20] [nvarchar](300) NULL,
[SALESCD20] [nvarchar](300) NULL,
[QTYSCD5] [nvarchar](300) NULL,
[SALESCD5] [nvarchar](300) NULL,
[QTYPWD] [nvarchar](300) NULL,
[SALEPWD] [nvarchar](300) NULL,
[QTYTGOVT] [nvarchar](300) NULL,
[SALESTGOVT] [nvarchar](300) NULL,
[QTYZERORATED] [nvarchar](300) NULL,
[SALESZERORATED] [nvarchar](300) NULL,
[QTYVATEXEMPT] [nvarchar](300) NULL,
[SALESVATEXEMPT] [nvarchar](300) NULL,
[TDISCOUNT] [nvarchar](300) NULL,
[DISCREGULARQTY] [nvarchar](300) NULL,
[DISCREGULARAMT] [nvarchar](300) NULL,
[DISCSCD20QTY] [nvarchar](300) NULL,
[DISCSCD20AMT] [nvarchar](300) NULL,
[DISCSCD5QTY] [nvarchar](300) NULL,
[DISCSCD5AMT] [nvarchar](300) NULL,
[DISCPWD20QTY] [nvarchar](300) NULL,
[DISCPWD20AMT] [nvarchar](300) NULL,
[DISCPWD5QTY] [nvarchar](300) NULL,
[DISCPWD5AMT] [nvarchar](300) NULL,
[DNETSALES] [nvarchar](300) NULL,
[DGROSSSALES] [nvarchar](300) NULL,
[SALESACCOUNTABILITY] [nvarchar](300) NULL,
[VOIDTRANQTY] [nvarchar](300) NULL,
[VOIDTRANAMT] [nvarchar](300) NULL,
[ITEMVOIDQTY] [nvarchar](300) NULL,
[ITEMVOIDAMT] [nvarchar](300) NULL,
[TICKETRETQTY] [nvarchar](300) NULL,
[TICKETRETAMT] [nvarchar](300) NULL,
[ITEMRETQTY] [nvarchar](300) NULL,
[ITEMRETAMT] [nvarchar](300) NULL,
[ADDLOANTOTQTY] [nvarchar](300) NULL,
[ADDLOANTOTAMT] [nvarchar](300) NULL,
[TENDERCASHQTY] [nvarchar](300) NULL,
[TENDERCASHAMT] [nvarchar](300) NULL,
[TENDERATMOFFLINEQTY] [nvarchar](300) NULL,
[TENDERATMOFFLINEAMT] [nvarchar](300) NULL,
[TENDERCHRGOFFLINEQTY] [nvarchar](300) NULL,
[TENDERCHRGOFFLINEAMT] [nvarchar](300) NULL,
[TENDERCHKQTY] [nvarchar](300) NULL,
[TENDERCHKAMT] [nvarchar](300) NULL,
[TENDERBDOREBATESQTY] [nvarchar](300) NULL,
[TENDERBDOREBATESAMT] [nvarchar](300) NULL,
[OVERTENDERQTY] [nvarchar](300) NULL,
[OVERTENDERAMT] [nvarchar](300) NULL,
[OTHERTENDERQTY] [nvarchar](300) NULL,
[OTHERTENDERAMT] [nvarchar](300) NULL,
[TENDERCCMQTY] [nvarchar](300) NULL,
[TENDERCCMAMT] [nvarchar](300) NULL,
[TENDERARCODQTY] [nvarchar](300) NULL,
[TENDERARCODAMT] [nvarchar](300) NULL,
[TENDERADBQTY] [nvarchar](300) NULL,
[TENDERADBAMT] [nvarchar](300) NULL,
[TENDERFWV5QTY] [nvarchar](300) NULL,
[TENDERFWV5AMT] [nvarchar](300) NULL,
[TENDEREWT1QTY] [nvarchar](300) NULL,
[TENDEREWT1AMT] [nvarchar](300) NULL,
[TENDERTOP20KQTY] [nvarchar](300) NULL,
[TENDERTOP20KAMT] [nvarchar](300) NULL,
[CCARDATMCHRGONLINEQTY] [nvarchar](300) NULL,
[CCARDATMCHRGONLINEAMT] [nvarchar](300) NULL,
[OTHTENDERSMGCQTY] [nvarchar](300) NULL,
[OTHTENDERSMGCAMT] [nvarchar](300) NULL,
[OTHTENDERSODEXOQTY] [nvarchar](300) NULL,
[OTHTENDERSODEXOAMT] [nvarchar](300) NULL,
[OTHTENDERCORPACCQTY] [nvarchar](300) NULL,
[OTHTENDERCORPACCAMT] [nvarchar](300) NULL,
[OTHTENDERDIFFEREDQTY] [nvarchar](300) NULL,
[OTHTENDERDIFFEREDAMT] [nvarchar](300) NULL,
[TENDERTOTAL] [nvarchar](300) NULL,
[VATSALEAMT] [nvarchar](300) NULL,
[VATSALETAXVALUE] [nvarchar](300) NULL,
[VATEXSALEAMT] [nvarchar](300) NULL,
[VATEXSALETAXVALUE] [nvarchar](300) NULL,
[ZERORATEDSALEAMT] [nvarchar](300) NULL,
[ZERORATEDSALETAXVALUE] [nvarchar](300) NULL,
[TOTALAMT] [nvarchar](300) NULL,
[TOTALTAXVALUE] [nvarchar](300) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[TermZTran] ([HeaderID], [WorkDate], [ProcessDate], [ProcessMode], [POSCount], [SalePharma], [SaleNonPharma], [VoidAmount], [VoidCount], [ZCOUNTER], [STORE], [POS], [DATE], [TIME], [OGTOTAL], [NGTOTAL], [BEGSI], [LASSI], [TSALES], [QTYREGULAR], [SALESREGULAR], [QTYSCD20], [SALESCD20], [QTYSCD5], [SALESCD5], [QTYPWD], [SALEPWD], [QTYTGOVT], [SALESTGOVT], [QTYZERORATED], [SALESZERORATED], [QTYVATEXEMPT], [SALESVATEXEMPT], [TDISCOUNT], [DISCREGULARQTY], [DISCREGULARAMT], [DISCSCD20QTY], [DISCSCD20AMT], [DISCSCD5QTY], [DISCSCD5AMT], [DISCPWD20QTY], [DISCPWD20AMT], [DISCPWD5QTY], [DISCPWD5AMT], [DNETSALES], [DGROSSSALES], [SALESACCOUNTABILITY], [VOIDTRANQTY], [VOIDTRANAMT], [ITEMVOIDQTY], [ITEMVOIDAMT], [TICKETRETQTY], [TICKETRETAMT], [ITEMRETQTY], [ITEMRETAMT], [ADDLOANTOTQTY], [ADDLOANTOTAMT], [TENDERCASHQTY], [TENDERCASHAMT], [TENDERATMOFFLINEQTY], [TENDERATMOFFLINEAMT], [TENDERCHRGOFFLINEQTY], [TENDERCHRGOFFLINEAMT], [TENDERCHKQTY], [TENDERCHKAMT], [TENDERBDOREBATESQTY], [TENDERBDOREBATESAMT], [OVERTENDERQTY], [OVERTENDERAMT], [OTHERTENDERQTY], [OTHERTENDERAMT], [TENDERCCMQTY], [TENDERCCMAMT], [TENDERARCODQTY], [TENDERARCODAMT], [TENDERADBQTY], [TENDERADBAMT], [TENDERFWV5QTY], [TENDERFWV5AMT], [TENDEREWT1QTY], [TENDEREWT1AMT], [TENDERTOP20KQTY], [TENDERTOP20KAMT], [CCARDATMCHRGONLINEQTY], [CCARDATMCHRGONLINEAMT], [OTHTENDERSMGCQTY], [OTHTENDERSMGCAMT], [OTHTENDERSODEXOQTY], [OTHTENDERSODEXOAMT], [OTHTENDERCORPACCQTY], [OTHTENDERCORPACCAMT], [OTHTENDERDIFFEREDQTY], [OTHTENDERDIFFEREDAMT], [TENDERTOTAL], [VATSALEAMT], [VATSALETAXVALUE], [VATEXSALEAMT], [VATEXSALETAXVALUE], [ZERORATEDSALEAMT], [ZERORATEDSALETAXVALUE], [TOTALAMT], [TOTALTAXVALUE]) VALUES (N'35a9637c-4342-4cb4-8f10-1c1d52b09cd4', CAST(0xA1A20000 AS SmallDateTime), CAST(0xA1A80478 AS SmallDateTime), N'sqljob', 1, 0.0000, 0.0000, 0.0000, 0, N'0001', N'0040', N'001', N'16/04/2013', N'19:06', N'0.00', N'73420.22', N'0000000001', N'0000000078', N'69827.81', N'75', N'48543.85', N'7', N'15683.96', N'4', N'940.00', N'6', N'4520.00', N'0', N'0.00', N'0', N'0.00', N'1', N'140.00', N'8283.98', N'30', N'4361.04', N'7', N'3136.79', N'4', N'41.96', N'3', N'723.21', N'3', N'20.98', N'56502.49', N'73420.22', N'61760.30', N'3', N'5815.95', N'-33', N'-1282.50', N'-14', N'-5886.00', N'-151', N'-3923.18', N'2', N'6000.00', N'68', N'46045.65', N'1', N'67.50', N'3', N'751.75', N'1', N'3200.00', N'2', N'310.82', N'2', N'-3.00', N'3', N'0.03', N'0', N'0.00', N'0', N'0.00', N'0', N'0', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'11', N'9096.12', N'5', N'800.00', N'5', N'450.00', N'1', N'1041.43', N'0', N'0.00', N'61760.30', N'43815.32', N'5257.81', N'15823.96', N'0.00', N'0.00', N'0.00', N'59639.28', N'5257.81')
INSERT [dbo].[TermZTran] ([HeaderID], [WorkDate], [ProcessDate], [ProcessMode], [POSCount], [SalePharma], [SaleNonPharma], [VoidAmount], [VoidCount], [ZCOUNTER], [STORE], [POS], [DATE], [TIME], [OGTOTAL], [NGTOTAL], [BEGSI], [LASSI], [TSALES], [QTYREGULAR], [SALESREGULAR], [QTYSCD20], [SALESCD20], [QTYSCD5], [SALESCD5], [QTYPWD], [SALEPWD], [QTYTGOVT], [SALESTGOVT], [QTYZERORATED], [SALESZERORATED], [QTYVATEXEMPT], [SALESVATEXEMPT], [TDISCOUNT], [DISCREGULARQTY], [DISCREGULARAMT], [DISCSCD20QTY], [DISCSCD20AMT], [DISCSCD5QTY], [DISCSCD5AMT], [DISCPWD20QTY], [DISCPWD20AMT], [DISCPWD5QTY], [DISCPWD5AMT], [DNETSALES], [DGROSSSALES], [SALESACCOUNTABILITY], [VOIDTRANQTY], [VOIDTRANAMT], [ITEMVOIDQTY], [ITEMVOIDAMT], [TICKETRETQTY], [TICKETRETAMT], [ITEMRETQTY], [ITEMRETAMT], [ADDLOANTOTQTY], [ADDLOANTOTAMT], [TENDERCASHQTY], [TENDERCASHAMT], [TENDERATMOFFLINEQTY], [TENDERATMOFFLINEAMT], [TENDERCHRGOFFLINEQTY], [TENDERCHRGOFFLINEAMT], [TENDERCHKQTY], [TENDERCHKAMT], [TENDERBDOREBATESQTY], [TENDERBDOREBATESAMT], [OVERTENDERQTY], [OVERTENDERAMT], [OTHERTENDERQTY], [OTHERTENDERAMT], [TENDERCCMQTY], [TENDERCCMAMT], [TENDERARCODQTY], [TENDERARCODAMT], [TENDERADBQTY], [TENDERADBAMT], [TENDERFWV5QTY], [TENDERFWV5AMT], [TENDEREWT1QTY], [TENDEREWT1AMT], [TENDERTOP20KQTY], [TENDERTOP20KAMT], [CCARDATMCHRGONLINEQTY], [CCARDATMCHRGONLINEAMT], [OTHTENDERSMGCQTY], [OTHTENDERSMGCAMT], [OTHTENDERSODEXOQTY], [OTHTENDERSODEXOAMT], [OTHTENDERCORPACCQTY], [OTHTENDERCORPACCAMT], [OTHTENDERDIFFEREDQTY], [OTHTENDERDIFFEREDAMT], [TENDERTOTAL], [VATSALEAMT], [VATSALETAXVALUE], [VATEXSALEAMT], [VATEXSALETAXVALUE], [ZERORATEDSALEAMT], [ZERORATEDSALETAXVALUE], [TOTALAMT], [TOTALTAXVALUE]) VALUES (N'35a9637c-4342-4cb4-8f10-1c1d52b09cd4', CAST(0xA1A20000 AS SmallDateTime), CAST(0xA1A80478 AS SmallDateTime), N'sqljob', 2, 0.0000, 0.0000, 0.0000, 0, N'0001', N'0040', N'002', N'16/04/2013', N'19:06', N'0.00', N'60296.14', N'0000000001', N'0000000076', N'58336.24', N'61', N'44770.01', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'7', N'4597.00', N'15', N'8269.23', N'4', N'700.00', N'3890.95', N'17', N'3890.95', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'49572.91', N'60296.14', N'54445.29', N'2', N'186.00', N'-133', N'-3567.50', N'-7', N'-6661.50', N'-90', N'-2085.50', N'2', N'6000.00', N'66', N'39251.01', N'1', N'67.50', N'1', N'149.00', N'0', N'0.00', N'0', N'0.00', N'3', N'-22.68', N'10', N'3989.88', N'0', N'0.00', N'0', N'0.00', N'0', N'0', N'11', N'205.23', N'11', N'41.05', N'13', N'41.05', N'8', N'4323.75', N'9', N'2500.00', N'1', N'100.00', N'2', N'3799.50', N'0', N'0.00', N'54445.29', N'40603.68', N'4872.38', N'700.00', N'0.00', N'8269.23', N'0.00', N'49572.91', N'4872.38')
INSERT [dbo].[TermZTran] ([HeaderID], [WorkDate], [ProcessDate], [ProcessMode], [POSCount], [SalePharma], [SaleNonPharma], [VoidAmount], [VoidCount], [ZCOUNTER], [STORE], [POS], [DATE], [TIME], [OGTOTAL], [NGTOTAL], [BEGSI], [LASSI], [TSALES], [QTYREGULAR], [SALESREGULAR], [QTYSCD20], [SALESCD20], [QTYSCD5], [SALESCD5], [QTYPWD], [SALEPWD], [QTYTGOVT], [SALESTGOVT], [QTYZERORATED], [SALESZERORATED], [QTYVATEXEMPT], [SALESVATEXEMPT], [TDISCOUNT], [DISCREGULARQTY], [DISCREGULARAMT], [DISCSCD20QTY], [DISCSCD20AMT], [DISCSCD5QTY], [DISCSCD5AMT], [DISCPWD20QTY], [DISCPWD20AMT], [DISCPWD5QTY], [DISCPWD5AMT], [DNETSALES], [DGROSSSALES], [SALESACCOUNTABILITY], [VOIDTRANQTY], [VOIDTRANAMT], [ITEMVOIDQTY], [ITEMVOIDAMT], [TICKETRETQTY], [TICKETRETAMT], [ITEMRETQTY], [ITEMRETAMT], [ADDLOANTOTQTY], [ADDLOANTOTAMT], [TENDERCASHQTY], [TENDERCASHAMT], [TENDERATMOFFLINEQTY], [TENDERATMOFFLINEAMT], [TENDERCHRGOFFLINEQTY], [TENDERCHRGOFFLINEAMT], [TENDERCHKQTY], [TENDERCHKAMT], [TENDERBDOREBATESQTY], [TENDERBDOREBATESAMT], [OVERTENDERQTY], [OVERTENDERAMT], [OTHERTENDERQTY], [OTHERTENDERAMT], [TENDERCCMQTY], [TENDERCCMAMT], [TENDERARCODQTY], [TENDERARCODAMT], [TENDERADBQTY], [TENDERADBAMT], [TENDERFWV5QTY], [TENDERFWV5AMT], [TENDEREWT1QTY], [TENDEREWT1AMT], [TENDERTOP20KQTY], [TENDERTOP20KAMT], [CCARDATMCHRGONLINEQTY], [CCARDATMCHRGONLINEAMT], [OTHTENDERSMGCQTY], [OTHTENDERSMGCAMT], [OTHTENDERSODEXOQTY], [OTHTENDERSODEXOAMT], [OTHTENDERCORPACCQTY], [OTHTENDERCORPACCAMT], [OTHTENDERDIFFEREDQTY], [OTHTENDERDIFFEREDAMT], [TENDERTOTAL], [VATSALEAMT], [VATSALETAXVALUE], [VATEXSALEAMT], [VATEXSALETAXVALUE], [ZERORATEDSALEAMT], [ZERORATEDSALETAXVALUE], [TOTALAMT], [TOTALTAXVALUE]) VALUES (N'35a9637c-4342-4cb4-8f10-1c1d52b09cd4', CAST(0xA1A20000 AS SmallDateTime), CAST(0xA1A80478 AS SmallDateTime), N'sqljob', 3, 0.0000, 0.0000, 0.0000, 0, N'0001', N'0040', N'003', N'16/04/2013', N'19:06', N'0.00', N'0.00', N'0000000000', N'0000000000', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0.00', N'0.00', N'0.00', N'1', N'0.01', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00', N'0.00')
Please help...
You have quite weird data schema. Did you try to store numeric values as decimal rather than as nvarchar. Possible this may should help -
SELECT BR_CODE
,N_CHECK
,CLAS_C
,CLAS_TRD_C
,STOR_NO
,SUM(TSL_NEW_A) AS TSL_NEW_A
,SUM(TSL_OLD_A) AS TSL_OLD_A
,SalesType
,SUM(TSL_DAY_A) AS TSL_DAY_A
,SUM(TSL_DIS_A) AS TSL_DIS_A
,TSL_DIS_B = 0
,SUM(TSL_DIS_C) AS TSL_DIS_C
,TSL_DIS_D = 0
,SUM(TSL_DIS_E) AS TSL_DIS_E
,TSL_Dis_F = 0
,TSL_Dis_G = 0
,TSL_Dis_H = 0
,TSL_Dis_I = 0
,TSL_Dis_J = 0
,TSL_Dis_K = 0
,TSL_Dis_L = 0
,SUM(TSL_TAX_A) AS TSL_TAX_A
,TSL_TAX_B = 0
,TSL_ADJ_A = 0
,TSL_ADJ_POS = 0
,TS_ADJ_NEG = 0
,TSL_ADJ_NT_POS = 0
,TSL_ADJ_NT_NEG = 0
,SUM(TSL_NET_A) AS TSL_NET_A
,SUM(TSL_VOID) AS TSL_VOID
,SUM(TSL_RFND) AS TSL_RFND
,SUM(TSL_TX_SAL) AS TSL_TX_SAL
,SUM(TSL_NX_SAL) AS TSL_NX_SAL
,TSL_CHG
,SUM(TSL_CSH) AS TSL_CSH
,SUM(TSL_GC) AS TSL_GC
,TSL_EPS = 0
,TSL_TND = 0
,TSL_MCRD = 0
,TSL_VISA = 0
,TSL_AMEX = 0
,TSL_DINERS = 0
,TSL_JBC = 0
,TSL_OTCRD = 0
,TSL_SV_CHG = 0
,TSL_OT_CHG = 0
,SUM(TSL_FT) AS TSL_FT
,SUM(TSL_LT) AS TSL_LT
,SUM(TSL_NT) AS TSL_NT
,SUM(TSL_BEG_INV) AS TSL_BEG_INV
,SUM(TSL_END_INV) AS TSL_END_INV
,SUM(TSL_TC_CASH) AS TSL_TC_CASH
,SUM(TSL_TC_GC) AS TSL_TC_GC
,TSL_TC_EPS = 0
,TSL_TC_TND = 0
,TSL_TC_MCD = 0
,TSL_TC_VIS = 0
,TSL_TC_AMX = 0
,TSL_TC_DIN = 0
,TSL_TC_JBC = 0
,TSL_TC_OC = 0
,TSL_MCH = 0
,TSL_SRL = 0
,SUM(TSL_ZCNT) AS TSL_ZCNT
,TSL_TIME
,TSL_DTE
FROM(
SELECT
BR_CODE
, N_CHECK
, CLAS_C
, CLAS_TRD_C
, STOR_NO
, SUM(TSL_NEW_A) AS TSL_NEW_A
, SUM(TSL_OLD_A) AS TSL_OLD_A
, SalesType
, SUM(TSL_DAY_A) AS TSL_DAY_A
, SUM(TSL_DIS_A) AS TSL_DIS_A
, SUM(TSL_DIS_C) AS TSL_DIS_C
, SUM(TSL_DIS_E) AS TSL_DIS_E
, SUM(TSL_TAX_A) AS TSL_TAX_A
, SUM(TSL_NET_A) AS TSL_NET_A
, SUM(TSL_VOID) AS TSL_VOID
, SUM(TSL_RFND) AS TSL_RFND
, SUM(TSL_TX_SAL) AS TSL_TX_SAL
, SUM(TSL_NX_SAL) AS TSL_NX_SAL
, TSL_CHG
, SUM(TSL_CSH) AS TSL_CSH
, SUM(TSL_GC) AS TSL_GC
, SUM(TSL_FT) AS TSL_FT
, SUM(TSL_LT) AS TSL_LT
, SUM(TSL_NT) AS TSL_NT
, SUM(TSL_BEG_INV) AS TSL_BEG_INV
, SUM(TSL_END_INV) AS TSL_END_INV
, SUM(TSL_TC_CASH) AS TSL_TC_CASH
, SUM(TSL_TC_GC) AS TSL_TC_GC
, SUM(TSL_ZCNT) AS TSL_ZCNT
, TSL_TIME
, TSL_DTE
FROM (
SELECT
BR_CODE = 0
, N_CHECK = 0
, CLAS_C = 0
, CLAS_TRD_C = 0
, STOR_NO = 0
, TSL_NEW_A = SUM(CAST(NGTOTAL AS DECIMAL(16,2)) + CAST(OGTOTAL AS DECIMAL(16,2)))
, TSL_OLD_A = SUM(CAST(OGTOTAL AS DECIMAL(16,2)))
, SalesType = 0
, SUM(((CAST(SALESREGULAR AS DECIMAL(16,2)) - CAST(SALESVATEXEMPT AS DECIMAL(16,2))) +
CAST(SALESCD20 AS DECIMAL(16,2)) +
CAST(SALESCD5 AS DECIMAL(16,2)) +
CAST(SALEPWD AS DECIMAL(16,2)) +
CAST(SALESTGOVT AS DECIMAL(16,2)) +
CAST(SALESZERORATED AS DECIMAL(16,2)) +
CAST(DISCREGULARAMT AS DECIMAL(16,2)) +
CAST(DISCSCD20AMT AS DECIMAL(16,2)) +
CAST(DISCSCD5AMT AS DECIMAL(16,2)) +
CAST(DISCPWD20AMT AS DECIMAL(16,2)) +
CAST(DISCPWD5AMT AS DECIMAL(16,2)) +
CAST(VOIDTRANAMT AS DECIMAL(16,2)) +
CAST(ITEMVOIDAMT AS DECIMAL(16,2)) +
CAST(TICKETRETAMT AS DECIMAL(16,2)) +
CAST(ITEMRETAMT AS DECIMAL(16,2)))/1.12) + CAST(SALESVATEXEMPT AS DECIMAL(16,2)) AS TSL_DAY_A --SUM(cast(round((cast(TSALES as decimal)/1.12),2) AS DECIMAL(16,2))) AS TSL_DAY_A --Help
,SUM(ABS(CAST(DISCREGULARAMT AS DECIMAL(16,2)))) AS TSL_DIS_A
,SUM(CAST(DISCSCD20AMT AS DECIMAL(16,2)) + CAST(DISCSCD5AMT AS DECIMAL(16,2))) AS TSL_DIS_C
,SUM(CAST(DISCSCD20AMT AS DECIMAL(16,2)) + CAST(DISCSCD5AMT AS DECIMAL(16,2))) AS TSL_DIS_E
,SUM(CAST(VATSALEAMT AS DECIMAL(16,2))) AS TSL_TAX_A
,SUM(CAST(DGROSSSALES AS DECIMAL(16,2)) - CAST(TOTALTAXVALUE AS DECIMAL(16,2))) AS TSL_NET_A --Help
,SUM(CAST(VOIDTRANAMT AS DECIMAL(16,2))) AS TSL_VOID
,SUM(ABS(CAST(ITEMRETAMT AS DECIMAL(16,2)))) AS TSL_RFND
,SUM(((CAST(SALESREGULAR AS DECIMAL(16,2)) + CAST(SALESVATEXEMPT AS DECIMAL(16,2))) +
CAST(SALESCD20 AS DECIMAL(16,2)) +
CAST(SALESCD5 AS DECIMAL(16,2)) +
CAST(SALEPWD AS DECIMAL(16,2)) +
CAST(SALESTGOVT AS DECIMAL(16,2)) +
CAST(SALESZERORATED AS DECIMAL(16,2)) +
CAST(DISCREGULARAMT AS DECIMAL(16,2)) +
CAST(DISCSCD20AMT AS DECIMAL(16,2)) +
CAST(DISCSCD5AMT AS DECIMAL(16,2)) +
CAST(DISCPWD20AMT AS DECIMAL(16,2)) +
CAST(DISCPWD5AMT AS DECIMAL(16,2)) +
CAST(VOIDTRANAMT AS DECIMAL(16,2)) +
CAST(ITEMVOIDAMT AS DECIMAL(16,2)) +
CAST(TICKETRETAMT AS DECIMAL(16,2)) +
CAST(ITEMRETAMT AS DECIMAL(16,2)))) AS TSL_TX_SAL --Help
,(CAST(SALESVATEXEMPT AS DECIMAL(16,2)) + (CAST(ZERORATEDSALEAMT AS DECIMAL(16,2)) - CAST(ZERORATEDSALETAXVALUE AS DECIMAL(16,2)))) AS TSL_NX_SAL
,SUM(CAST(CCARDATMCHRGONLINEAMT AS DECIMAL(16,2))) AS TSL_CHG --Help
,SUM(CAST(TENDERCASHAMT AS DECIMAL(16,2))) AS TSL_CSH
,SUM(CAST(OTHTENDERSMGCAMT AS DECIMAL(16,2)) + CAST(OTHTENDERSODEXOAMT AS DECIMAL(16,2))) AS TSL_GC --+ CAST(TENDERCHKAMT AS DECIMAL) AS TSL_GC
,SUM(CAST(ABS(BEGSI) AS INT)) AS TSL_FT
,SUM(CAST(ABS(LASSI) AS INT)) AS TSL_LT
,SUM(CAST((CAST(QTYREGULAR AS DECIMAL(18,2)) + CAST(QTYSCD20 AS DECIMAL(18,2)) + CAST(QTYSCD5 AS DECIMAL(18,2)) + CAST(QTYPWD AS DECIMAL(18,2)) + CAST(QTYTGOVT AS DECIMAL(18,2)) + CAST(QTYZERORATED AS DECIMAL(18,2))
+ CAST(QTYVATEXEMPT AS DECIMAL(18,2)) + CAST(DISCREGULARQTY AS DECIMAL(18,2)) + CAST(DISCSCD20QTY AS DECIMAL(18,2)) + CAST(DISCSCD5QTY AS DECIMAL(18,2)) + CAST(DISCPWD20QTY AS DECIMAL(18,2))
+ CAST(DISCPWD5QTY AS DECIMAL(18,2)) + CAST(VOIDTRANQTY AS DECIMAL(18,2)) + CAST(ITEMVOIDQTY AS DECIMAL(18,2))*-1 + CAST(TICKETRETQTY AS DECIMAL(18,2))*-1 + CAST(ITEMRETQTY AS DECIMAL(18,2))*-1
+ CAST(ADDLOANTOTQTY AS DECIMAL(18,2))) AS INT)) AS TSL_NT
,SUM(CAST(ABS(BEGSI) AS INT)) AS TSL_BEG_INV
,SUM(CAST(ABS(LASSI) AS INT)) AS TSL_END_INV
,SUM(CAST(QTYREGULAR AS INT)) as TSL_TC_CASH
,SUM(CAST(OTHTENDERSMGCQTY AS INT) + CAST(OTHTENDERSODEXOQTY AS INT)) AS TSL_TC_GC
,SUM(CAST(ABS(ZCOUNTER) AS INT)) AS TSL_ZCNT
,RIGHT('00'+RTRIM(CAST(DATEPART(HH,GETDATE())AS VARCHAR(5))),2)+RIGHT('00'+RTRIM(CAST(DATEPART(MI,GETDATE()) AS VARCHAR(5))),2)+RIGHT('00'+RTRIM(CAST(DATEPART(SS,GETDATE()) AS VARCHAR(5))),2) AS TSL_TIME
,SUBSTRING(convert(varchar,WorkDate,111),6,2)+Right(convert(varchar,WorkDate,111),2)+left(convert(varchar,WorkDate,111),4) AS TSL_DTE
FROM dbo.TermZTran t
LEFT JOIN (
SELECT sLessee, sTenantNumber AS TenantCode, sStoreNumber
FROM mLandlordStore
) tInfo ON t.STORE = tInfo.sStoreNumber
WHERE CAST(t.Store AS INT) = CAST(#branchcode AS INT)
AND tInfo.sLessee = #lesseeCode
AND CONVERT(nvarchar(10),t.WorkDate,101) = #trandate
AND CONVERT(nvarchar(10),t.WorkDate,101) = '04/16/2013'
AND CAST(BR_CODE AS INT) = CAST('0040' AS INT)
GROUP BY
SALESVATEXEMPT
, ZERORATEDSALEAMT
, ZERORATEDSALETAXVALUE
, WorkDate
) tFinal
GROUP BY
BR_CODE
,N_CHECK
,CLAS_C
,CLAS_TRD_C
,STOR_NO
,TSL_NEW_A
,TSL_OLD_A
,SalesType
,TSL_DAY_A
,TSL_DIS_A
,TSL_DIS_C
,TSL_DIS_E
,TSL_TAX_A
,TSL_NET_A
,TSL_VOID
,TSL_RFND
,TSL_TX_SAL
,TSL_NX_SAL
,TSL_CHG
,TSL_CSH
,TSL_GC
,TSL_FT
,TSL_LT
,TSL_NT
,TSL_BEG_INV
,TSL_END_INV
,TSL_TC_CASH
,TSL_TC_GC
,TSL_ZCNT
,TSL_TIME
,TSL_DTE
) dt
GROUP BY
dt.BR_CODE
,dt.CLAS_C
,dt.CLAS_TRD_C
,dt.N_CHECK
,dt.STOR_NO
,dt.SalesType
,TSL_DAY_A
,TSL_DIS_A
,TSL_DIS_C
,TSL_DIS_E
,TSL_TAX_A
,TSL_NET_A
,TSL_VOID
,TSL_RFND
,TSL_TX_SAL
,TSL_NX_SAL
,TSL_CHG
,TSL_CSH
,TSL_GC
,TSL_FT
,TSL_LT
,TSL_NT
,TSL_BEG_INV
,TSL_END_INV
,TSL_TC_CASH
,TSL_TC_GC
,TSL_ZCNT
,TSL_TIME
,TSL_DTE
Related
Produce XML from MS SQL, structure issues, namespace prefix:
I'm trying to run SQL for complex XML out of MS SQL Server 2016. I made a huge progress considering that I'm new to XML generation but still can't figure out how to do that nesting portion to make Export/Client structure matter what I tried putting into nested ROOT clause. Not sure if this issue also causing that I'm missing hmis: prefix for most Elements. I need them like on attached picture with Desired output/schema. Also pasting self containing test Input and working code , I marked with ???? places which I think caused this trouble. Appreciate your hints. Do you think it's will be easy to do with other types FOR XML ? Explicit ??? Best Mario SQL Version: Microsoft SQL Server 2017 (RTM-CU27) Updated: added #export table /* --- test data/table DROP TABLE IF EXISTS #t; SELECT * INTO #T FROM ( -- SELECT * FROM #T SELECT 111 PersonalID, 'Alpha' first_name, 'Brown' last_name, '1/1/2000' birth_date, 'Manager Alpha' CaseManager_PH, 0 Female, '3/2/2022' ExportDate, 'AW3' user_updated UNION SELECT 222 PersonalID, 'Bobby' , 'Dow' , '2/2/2002', 'Manager2222' , 0 , '3/3/2022' ExportDate, 'BBX3' ) A SELECT * FROM #T */ DECLARE #export TABLE ( ExportDate date , StartDate DATE, EndDate date) INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES ('3/22/2022', '1/1/2022', '4/4/2022') ; WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis, 'http://www.w3.org/2001/XMLSchema-instance' AS xsi ) SELECT 10 AS [hmis:SourceID], 111 AS [hmis:Export/ExportID] ,CAST(e.ExportDate AS VARCHAR(10)) AS [hmis:Export/ExportDate] ---<<< Change ,CAST(e.StartDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/StartDate] ,CAST(e.EndDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/EndDate] , ( SELECT ExportDate AS [hmis:Client/#DateCreated], ExportDate AS [hmis:Client/#dateUpdated], PersonalID AS [hmis:Client/PersonalID], first_name AS [hmis:Client/first_name], last_name AS [hmis:Client/last_name], birth_date AS [hmis:Client/birth_date], CaseManager_PH AS [hmis:Client/CustomClientElements/CaseManager_PH], 'Unknown' AS [hmis:Client/CustomClientElements/Casemanager_ContactInfo], user_updated AS [hmis:Client/user_updated] FROM #t t -- WHERE 1=1 FOR XML path , ROOT('Export'), TYPE) ---???? FROM #export e FOR XML PATH('Source'), ROOT('Sources') Desired output format: <hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd"> <hmis:Source> <hmis:SourceID>10</hmis:SourceID> <hmis:Export> <ExportID>111</ExportID> <ExportDate>2022-03-22</ExportDate> <ExportPeriod> <StartDate>2022-01-01</StartDate> <EndDate>2022-04-04</EndDate> </ExportPeriod> <hmis:Client DateCreated="3/2/2022" DateUpdated="3/2/2022"> <hmis:PersonalID>111</hmis:PersonalID> <hmis:first_name>Alpha</hmis:first_name> <hmis:last_name>Brown</hmis:last_name> <hmis:birth_date>1/1/2000</hmis:birth_date> <hmis:CustomClientElements> <hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH> <hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>AW3</hmis:user_updated> </hmis:Client> <hmis:Client DateCreated="3/3/2022" DateUpdated="3/3/2022"> <hmis:PersonalID>222</hmis:PersonalID> <hmis:first_name>Bobby</hmis:first_name> <hmis:last_name>Dow</hmis:last_name> <hmis:birth_date>2/2/2002</hmis:birth_date> <hmis:CustomClientElements> <hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH> <hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>BBX3</hmis:user_updated> </hmis:Client> </hmis:Export> </hmis:Source> </hmis:Sources>
Please try the following solution. The desired output is produced in two steps: Raw XML via FOR XML PATH('r'), TYPE, ROOT('root'). Fine tuned final XML via XQuery .query() method and FLWOR expression. Because a minimal reproducible example is not provided, I hope I didn't miss anything. SQL -- DDL and sample data population, start DECLARE #tbl TABLE ( PersonalID INT PRIMARY KEY, first_name VARCHAR(30), last_name VARCHAR(30), birth_date DATE, CaseManager_PH VARCHAR(30), Female BIT, ExportDate DATE, user_updated VARCHAR(30) ); INSERT INTO #tbl ( PersonalID, first_name, last_name, birth_date, CaseManager_PH, Female, ExportDate, user_updated ) VALUES (111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'), (222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3'); DECLARE #export TABLE (ExportDate date , StartDate DATE, EndDate date); INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES ('2022-03-22', '2022-01-01', '2022-04-04'); -- DDL and sample data population, end DECLARE #ExportDate date, #StartDate DATE, #EndDate DATE; SELECT #ExportDate = ExportDate, #StartDate = StartDate, #EndDate = EndDate FROM #export; WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis, 'http://www.w3.org/2001/XMLSchema-instance' AS xsi ) SELECT ( SELECT * FROM #tbl FOR XML PATH('r'), TYPE, ROOT('root')) .query('<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <hmis:Source> <hmis:SourceID>10</hmis:SourceID> <hmis:Export> <ExportID>111</ExportID> <ExportDate>{sql:variable("#ExportDate")}</ExportDate> <ExportPeriod> <StartDate>{sql:variable("#StartDate")}</StartDate> <EndDate>{sql:variable("#EndDate")}</EndDate> </ExportPeriod> { for $x in /root/r return <hmis:Client DateCreated="{$x/ExportDate}" DateUpdated="{$x/ExportDate}"> <hmis:PersonalID>{data($x/PersonalID)}</hmis:PersonalID> <hmis:first_name>{data($x/first_name)}</hmis:first_name> <hmis:last_name>{data($x/last_name)}</hmis:last_name> <hmis:birth_date>{data($x/birth_date)}</hmis:birth_date> <hmis:CustomClientElements> <hmis:CaseManager_PH>{data($x/CaseManager_PH)}</hmis:CaseManager_PH> <hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>{data($x/user_updated)}</hmis:user_updated> </hmis:Client> } </hmis:Export> </hmis:Source></hmis:Sources>'); Output <hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd"> <hmis:Source> <hmis:SourceID>10</hmis:SourceID> <hmis:Export> <ExportID>111</ExportID> <ExportDate>0</ExportDate> <ExportPeriod> <StartDate>0</StartDate> <EndDate>0</EndDate> </ExportPeriod> <hmis:Client DateCreated="2022-03-02" DateUpdated="2022-03-02"> <hmis:PersonalID>111</hmis:PersonalID> <hmis:first_name>Alpha</hmis:first_name> <hmis:last_name>Brown</hmis:last_name> <hmis:birth_date>2000-01-01</hmis:birth_date> <hmis:CustomClientElements> <hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH> <hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>AW3</hmis:user_updated> </hmis:Client> <hmis:Client DateCreated="2022-03-03" DateUpdated="2022-03-03"> <hmis:PersonalID>222</hmis:PersonalID> <hmis:first_name>Bobby</hmis:first_name> <hmis:last_name>Dow</hmis:last_name> <hmis:birth_date>2000-01-01</hmis:birth_date> <hmis:CustomClientElements> <hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH> <hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>BBX3</hmis:user_updated> </hmis:Client> </hmis:Export> </hmis:Source> </hmis:Sources>
You mentioned Explicit, so here is solution generated with FOAM. Not that pretty for some but works OK though could have some limitation with super fancy formats and some casese with maxOccurs="0". It also might require some manual tweaking. I made single table c just as my personal preference, which required me to add top 1 into few levels manually. But also works fine with join /* --------------------TEST DATA drop table if exists #tbl Create table #tbl ( PersonalID INT , first_name VARCHAR(30), last_name VARCHAR(30), birth_date DATE, CaseManager_PH VARCHAR(30), Female BIT, ExportDate DATE, user_updated VARCHAR(30) ); INSERT INTO #tbl VALUES (111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'), (222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3'); create table #export (ExportDate date , StartDate DATE, EndDate date); INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES ('2022-03-22', '2022-01-01', '2022-04-04'); -- select * from #export -- select * from #tbl -- drop table c Select * into c from ( select c.*, e.StartDate, e.EndDate , hmis =cast('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as varchar(255)) , ExportID = '111', SourceID = '10', ContactInfo = 'Unknown' from #tbl c join #export e on 1=1 ) c Select * from c */ /******************************************** * Output produced by Foam # * 3/31/2022 12:12:03 PM * * digital nothing design * http://www.digitalnothing.com ********************************************/ SELECT Tag = 1, Parent = NULL, [hmis:Sources!1!xmlns:hmis] = 'https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd', [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = NULL, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = NULL, [hmis:Export!3!ExportDate!element] = NULL, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = NULL, [ExportPeriod!4!EndDate!element] = NULL, [hmis:Client!5!DateCreated] = NULL, [hmis:Client!5!DateUpdated] = NULL, [hmis:Client!5!hmis:PersonalID!element] = NULL, [hmis:Client!5!hmis:first_name!element] = NULL, [hmis:Client!5!hmis:last_name!element] = NULL, [hmis:Client!5!hmis:birth_date!element] = NULL, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL, [hmis:Client!5!hmis:user_updated!element] = NULL UNION ALL SELECT top 1 Tag = 2, Parent = 1, [hmis:Sources!1!xmlns:hmis] = NULL, [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = c.SourceID, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = NULL, [hmis:Export!3!ExportDate!element] = NULL, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = NULL, [ExportPeriod!4!EndDate!element] = NULL, [hmis:Client!5!DateCreated] = NULL, [hmis:Client!5!DateUpdated] = NULL, [hmis:Client!5!hmis:PersonalID!element] = NULL, [hmis:Client!5!hmis:first_name!element] = NULL, [hmis:Client!5!hmis:last_name!element] = NULL, [hmis:Client!5!hmis:birth_date!element] = NULL, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL, [hmis:Client!5!hmis:user_updated!element] = NULL from c UNION ALL SELECT top 1 Tag = 3, Parent = 2, [hmis:Sources!1!xmlns:hmis] = NULL, [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = NULL, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = c.ExportID, [hmis:Export!3!ExportDate!element] = c.ExportDate, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = NULL, [ExportPeriod!4!EndDate!element] = NULL, [hmis:Client!5!DateCreated] = NULL, [hmis:Client!5!DateUpdated] = NULL, [hmis:Client!5!hmis:PersonalID!element] = NULL, [hmis:Client!5!hmis:first_name!element] = NULL, [hmis:Client!5!hmis:last_name!element] = NULL, [hmis:Client!5!hmis:birth_date!element] = NULL, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL, [hmis:Client!5!hmis:user_updated!element] = NULL from c UNION ALL SELECT top 1 Tag = 4, Parent = 3, [hmis:Sources!1!xmlns:hmis] = NULL, [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = NULL, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = NULL, [hmis:Export!3!ExportDate!element] = NULL, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = c.StartDate, [ExportPeriod!4!EndDate!element] = c.EndDate, [hmis:Client!5!DateCreated] = NULL, [hmis:Client!5!DateUpdated] = NULL, [hmis:Client!5!hmis:PersonalID!element] = NULL, [hmis:Client!5!hmis:first_name!element] = NULL, [hmis:Client!5!hmis:last_name!element] = NULL, [hmis:Client!5!hmis:birth_date!element] = NULL, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL, [hmis:Client!5!hmis:user_updated!element] = NULL from c UNION ALL SELECT Tag = 5, Parent = 3, [hmis:Sources!1!xmlns:hmis] = NULL, [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = NULL, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = NULL, [hmis:Export!3!ExportDate!element] = NULL, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = NULL, [ExportPeriod!4!EndDate!element] = NULL, [hmis:Client!5!DateCreated] = c.ExportDate, [hmis:Client!5!DateUpdated] = c.ExportDate, [hmis:Client!5!hmis:PersonalID!element] = c.PersonalID, [hmis:Client!5!hmis:first_name!element] = c.first_name, [hmis:Client!5!hmis:last_name!element] = c.last_name, [hmis:Client!5!hmis:birth_date!element] = c.birth_date, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL, [hmis:Client!5!hmis:user_updated!element] = c.user_updated from c UNION ALL SELECT Tag = 6, Parent = 5, [hmis:Sources!1!xmlns:hmis] = NULL, [hmis:Source!2!] = NULL, [hmis:Source!2!hmis:SourceID!element] = NULL, [hmis:Export!3!] = NULL, [hmis:Export!3!ExportID!element] = NULL, [hmis:Export!3!ExportDate!element] = NULL, [ExportPeriod!4!] = NULL, [ExportPeriod!4!StartDate!element] = NULL, [ExportPeriod!4!EndDate!element] = NULL, [hmis:Client!5!DateCreated] = NULL, [hmis:Client!5!DateUpdated] = NULL, [hmis:Client!5!hmis:PersonalID!element] = c.PersonalID, [hmis:Client!5!hmis:first_name!element] = NULL, [hmis:Client!5!hmis:last_name!element] = NULL, [hmis:Client!5!hmis:birth_date!element] = NULL, [hmis:CustomClientElements!6!] = NULL, [hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = ISNULL(c.Casemanager_PH,''), [hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = ISNULL(c.ContactInfo,''), [hmis:Client!5!hmis:user_updated!element] = NULL from c ORDER BY [hmis:Client!5!hmis:PersonalID!element] ASC, Tag FOR XML EXPLICIT -- sample xml with column names as element values used in FOAM /* <hmis:Sources xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd" > <hmis:Source> <hmis:SourceID>c.SourceID</hmis:SourceID> <hmis:Export> <ExportID>c.ExportID</ExportID> <ExportDate>c.ExportDate</ExportDate> <ExportPeriod> <StartDate>c.StartDate</StartDate> <EndDate>c.EndDate</EndDate> </ExportPeriod> <hmis:Client DateCreated = "c.ExportDate" DateUpdated="c.ExportDate" > <hmis:PersonalID>c.PersonalID</hmis:PersonalID> <hmis:first_name>c.first_name</hmis:first_name> <hmis:last_name>c.last_name</hmis:last_name> <hmis:birth_date>c.birth_date</hmis:birth_date> <hmis:CustomClientElements> <hmis:Casemanager_PH>c.Casemanager_PH</hmis:Casemanager_PH> <hmis:Casemanager_ContactInfo>c.ContactInfo</hmis:Casemanager_ContactInfo> </hmis:CustomClientElements> <hmis:user_updated>c.user_updated</hmis:user_updated> </hmis:Client> </hmis:Export> </hmis:Source> </hmis:Sources> */
SSRS Report Subscriptions: How can I tell when a recipient in a subscription was sent the SSRS report?
How can I tell when a recipient in a subscription was sent the SSRS report? I've seen similar questions but they seem to relate to which email addresses are currently subscribed to the report, rather than specific instances of when an email was sent to the recipient(s).
I've used this SQL script to find the execution log of subscriptions. There are some example reports in my GitHub project. USE [ReportServer]; GO DECLARE #StartDate DATETIME = '03-MAR-2022'; DECLARE #EndDate DATETIME = '04-MAR-2022'; DECLARE #ReportFolder NVARCHAR(200) = NULL; DECLARE #ReportName NVARCHAR(200) = NULL; DECLARE #LogStatus NVARCHAR(200) = NULL; DECLARE #StatusGroup NVARCHAR(200) = NULL; DECLARE #ServiceAccount NVARCHAR(200) = 'your_service_account'; -- enter the subscription service account here WITH report_status AS ( SELECT tbl.* FROM (VALUES ( 'rrRenderingError', 'Failure') , ( 'rsHttpRuntimeClientDisconnectionError', 'Failure') , ( 'rsInternalError', 'Failure') , ( 'rsInvalidDataSourceCredentialSetting', 'Failure') , ( 'rsProcessingAborted', 'Failure') , ( 'rsProcessingError', 'Failure') , ( 'rsRenderingExtensionNotFound', 'Failure') , ( 'rsReportServerDatabaseError', 'Failure') , ( 'rsSuccess', 'Success') ) tbl ([StatusName], [StatusGroup]) ) , report_users AS ( SELECT [UserID] , [UserName] , [SimpleUserName] = LOWER(RIGHT([UserName], (LEN([UserName]) - CHARINDEX('\', [UserName])))) FROM [dbo].[Users] WITH(NOLOCK) ) , report_catalog AS ( SELECT rpt.[ItemID] , rpt.[CreatedById] , rpt.[ModifiedById] , rpt.[Type] , rpt.[Name] , [ReportName] = rpt.[Name] , rpt.[Description] , rpt.[Parameter] , [CreationDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[CreationDate], 13)) , [ModifiedDate] = CONVERT(DATETIME, CONVERT(VARCHAR(11), rpt.[ModifiedDate], 13)) , [ReportFolder] = SUBSTRING(rpt.[Path], 2, Len(rpt.[Path])-Len(rpt.[Name])-2) , rpt.[Path] , [URL_ReportFolder] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, Len(rpt.[Path])-Len(rpt.[Name])-2) + '&ViewMode=List' , [URL_Report] = 'http://' + Host_Name() + '/Reports/Pages/Report.aspx?ItemPath=%2f' + SUBSTRING(rpt.[Path], 2, Len(rpt.[Path])-Len(rpt.[Name])-2) + '%2f' + rpt.[Name] , [ReportDefinition] = CONVERT(VARCHAR(MAX), CONVERT(VARBINARY(MAX), rpt.[Content])) FROM [dbo].[Catalog] AS rpt WITH (NOLOCK) WHERE 1=1 AND rpt.[Type] = 2 ) , subscription_days AS ( SELECT tbl.* FROM (VALUES ( 'DaysOfMonth', 1, '1') , ( 'DaysOfMonth', 2, '2') , ( 'DaysOfMonth', 4, '3') , ( 'DaysOfMonth', 8, '4') , ( 'DaysOfMonth', 16, '5') , ( 'DaysOfMonth', 32, '6') , ( 'DaysOfMonth', 64, '7') , ( 'DaysOfMonth', 128, '8') , ( 'DaysOfMonth', 256, '9') , ( 'DaysOfMonth', 512, '10') , ( 'DaysOfMonth', 1024, '11') , ( 'DaysOfMonth', 2048, '12') , ( 'DaysOfMonth', 4096, '13') , ( 'DaysOfMonth', 8192, '14') , ( 'DaysOfMonth', 16384, '15') , ( 'DaysOfMonth', 32768, '16') , ( 'DaysOfMonth', 65536, '17') , ( 'DaysOfMonth', 131072, '18') , ( 'DaysOfMonth', 262144, '19') , ( 'DaysOfMonth', 524288, '20') , ( 'DaysOfMonth', 1048576, '21') , ( 'DaysOfMonth', 2097152, '22') , ( 'DaysOfMonth', 4194304, '23') , ( 'DaysOfMonth', 8388608, '24') , ( 'DaysOfMonth', 16777216, '25') , ( 'DaysOfMonth', 33554432, '26') , ( 'DaysOfMonth', 67108864, '27') , ( 'DaysOfMonth', 134217728, '28') , ( 'DaysOfMonth', 268435456, '29') , ( 'DaysOfMonth', 536870912, '30') , ( 'DaysOfMonth', 1073741824, '31') , ( 'DaysOfMonth', 8193, '1st and 14th') , ( 'DaysOfWeek', 1, 'Sun') , ( 'DaysOfWeek', 2, 'Mon') , ( 'DaysOfWeek', 4, 'Tues') , ( 'DaysOfWeek', 8, 'Wed') , ( 'DaysOfWeek', 16, 'Thurs') , ( 'DaysOfWeek', 32, 'Fri') , ( 'DaysOfWeek', 64, 'Sat') , ( 'DaysOfWeek', 62, 'Mon - Fri') , ( 'DaysOfWeek', 10, 'Mon - Wed') , ( 'DaysOfWeek', 24, 'Wed - Thurs') , ( 'DaysOfWeek', 120, 'Wed - Sat') , ( 'DaysOfWeek', 126, 'Mon - Sat') , ( 'DaysOfWeek', 127, 'Daily') , ( 'DayOfWeek', 1, 'Sun') , ( 'DayOfWeek', 127, 'Sun') , ( 'DayOfWeek', 2, 'Mon') , ( 'DayOfWeek', 10, 'Mon') , ( 'DayOfWeek', 62, 'Mon') , ( 'DayOfWeek', 126, 'Mon') , ( 'DayOfWeek', 127, 'Mon') , ( 'DayOfWeek', 4, 'Tue') , ( 'DayOfWeek', 10, 'Tue') , ( 'DayOfWeek', 62, 'Tue') , ( 'DayOfWeek', 126, 'Tue') , ( 'DayOfWeek', 127, 'Tue') , ( 'DayOfWeek', 8, 'Wed') , ( 'DayOfWeek', 10, 'Wed') , ( 'DayOfWeek', 24, 'Wed') , ( 'DayOfWeek', 62, 'Wed') , ( 'DayOfWeek', 120, 'Wed') , ( 'DayOfWeek', 126, 'Wed') , ( 'DayOfWeek', 127, 'Wed') , ( 'DayOfWeek', 16, 'Thr') , ( 'DayOfWeek', 24, 'Thr') , ( 'DayOfWeek', 62, 'Thr') , ( 'DayOfWeek', 120, 'Thr') , ( 'DayOfWeek', 126, 'Thr') , ( 'DayOfWeek', 127, 'Thr') , ( 'DayOfWeek', 32, 'Fri') , ( 'DayOfWeek', 62, 'Fri') , ( 'DayOfWeek', 120, 'Fri') , ( 'DayOfWeek', 126, 'Fri') , ( 'DayOfWeek', 127, 'Fri') , ( 'DayOfWeek', 64, 'Sat') , ( 'DayOfWeek', 120, 'Sat') , ( 'DayOfWeek', 126, 'Sat') , ( 'DayOfWeek', 127, 'Sat') ) tbl ([GroupName], [CodeNbr], [Label]) ) , subscription_schedule AS ( SELECT [ScheduleID] , [SchDaySun] = Sun , [SchDayMon] = Mon , [SchDayTue] = Tue , [SchDayWed] = Wed , [SchDayThr] = Thr , [SchDayFri] = Fri , [SchDaySat] = Sat , [ScheduleName] , [ScheduleStartDate] , [ScheduleEndDate] , [Flags] , [RecurrenceType] , [State] , [MinutesInterval] , [DaysInterval] , [WeeksInterval] , [DaysOfWeek] , [DaysOfMonth] , [Month] , [MonthlyWeek] , [ScheduleDays] FROM ( SELECT sc.[ScheduleID] , sd.[CodeNbr] , sd.[Label] , [ScheduleName] = CASE WHEN sc.[EventType] = 'SharedSchedule' THEN sc.[name] ELSE NULL END , [ScheduleStartDate] = sc.[StartDate] , [ScheduleEndDate] = sc.[EndDate] , sc.[Flags] , sc.[RecurrenceType] , sc.[State] , sc.[MinutesInterval] , sc.[DaysInterval] , sc.[WeeksInterval] , sc.[DaysOfWeek] , sc.[DaysOfMonth] , sc.[Month] , sc.[MonthlyWeek] , [ScheduleDays] = CASE WHEN sc.[DaysOfMonth] IS NOT NULL THEN COALESCE(dom.[Label], '(' + CAST(sc.[DaysOfMonth] AS VARCHAR(20)) + ') NOT CODED') WHEN sc.[DaysOfWeek] IS NOT NULL THEN COALESCE(dow.[Label], '(' + CAST(sc.[DaysOfWeek] AS VARCHAR(20)) + ') NOT CODED') END FROM [dbo].[Schedule] sc WITH (NOLOCK) LEFT JOIN subscription_days sd ON sc.[DaysOfWeek] = sd.[CodeNbr] AND sd.[GroupName] = 'DayOfWeek' LEFT JOIN subscription_days AS dom ON sc.[DaysOfMonth] = dom.[CodeNbr] AND dom.[GroupName] = 'DaysOfMonth' LEFT JOIN subscription_days AS dow ON sc.[DaysOfWeek] = dow.[CodeNbr] AND dow.[GroupName] = 'DaysOfWeek' ) sch PIVOT ( COUNT(sch.[Label]) FOR sch.[Label] IN ([Sun], [Mon], [Tue], [Wed], [Thr], [Fri], [Sat]) ) AS pvt ) , report_subscription AS ( SELECT sub.[SubscriptionID] , sub.[Report_OID] , [SubscriptionDescription] = sub.[Description] , sub.[ExtensionSettings] , sub.[EventType] , sub.[OwnerID] , sub.[ModifiedByID] , sub.[ModifiedDate] , [RunTime] = CONVERT(VARCHAR(5), sub.[LastRunTime], 8) , [LastRunDate] = CONVERT(VARCHAR(11), sub.[LastRunTime], 13) , [LastRunTime] = CAST(CONVERT(CHAR(16), sub.[LastRunTime], 113) AS DATETIME) , sub.[DeliveryExtension] , sub.[MatchData] , [SubscriptionLastStatus] = sub.[LastStatus] , [StatusFail] = CASE WHEN sub.[LastStatus] LIKE '%Mail sent%' THEN 'N' ELSE 'Y' END , [EmailSubject] = CASE CHARINDEX('<Name>SUBJECT</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>SUBJECT</Name><Value>') + CHARINDEX('<Name>SUBJECT</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>SUBJECT</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>SUBJECT</Name><Value>') + CHARINDEX('<Name>SUBJECT</Name><Value>', sub.ExtensionSettings))) END , [EmailTo] = SUBSTRING(sub.ExtensionSettings, LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>TO</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>TO</Name><Value>') + CHARINDEX('<Name>TO</Name><Value>', sub.ExtensionSettings))) , [EmailCc] = CASE CHARINDEX('<Name>CC</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>CC</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>CC</Name><Value>') + CHARINDEX('<Name>CC</Name><Value>', sub.ExtensionSettings))) END , [EmailBcc] = CASE CHARINDEX('<Name>BCC</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>BCC</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>BCC</Name><Value>') + CHARINDEX('<Name>BCC</Name><Value>', sub.ExtensionSettings))) END , [EmailComment] = CASE CHARINDEX('<Name>Comment</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>Comment</Name><Value>') + CHARINDEX('<Name>Comment</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>Comment</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>Comment</Name><Value>') + CHARINDEX('<Name>Comment</Name><Value>', sub.ExtensionSettings))) END , [EmailIncludeLink] = CASE CHARINDEX('<Name>IncludeLink</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>IncludeLink</Name><Value>') + CHARINDEX('<Name>IncludeLink</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>IncludeLink</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>IncludeLink</Name><Value>') + CHARINDEX('<Name>IncludeLink</Name><Value>', sub.ExtensionSettings))) END , [EmailRenderFormat] = CASE CHARINDEX('<Name>RenderFormat</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>RenderFormat</Name><Value>') + CHARINDEX('<Name>RenderFormat</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>RenderFormat</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>RenderFormat</Name><Value>') + CHARINDEX('<Name>RenderFormat</Name><Value>', sub.ExtensionSettings))) END , [EmailPriority] = CASE CHARINDEX('<Name>Priority</Name><Value>', sub.ExtensionSettings) WHEN 0 THEN '' ELSE SUBSTRING(sub.ExtensionSettings, LEN('<Name>Priority</Name><Value>') + CHARINDEX('<Name>Priority</Name><Value>', sub.ExtensionSettings), CHARINDEX('</Value>', sub.ExtensionSettings, CHARINDEX('<Name>Priority</Name><Value>', sub.ExtensionSettings) + 1) - (LEN('<Name>Priority</Name><Value>') + CHARINDEX('<Name>Priority</Name><Value>', sub.ExtensionSettings))) END , sch.[MinutesInterval] , sch.[DaysInterval] , sch.[WeeksInterval] , sch.[DaysOfWeek] , sch.[DaysOfMonth] , sch.[Month] , sch.[MonthlyWeek] , sch.[ScheduleName] , sch.[ScheduleDays] , sch.[SchDaySun] , sch.[SchDayMon] , sch.[SchDayTue] , sch.[SchDayWed] , sch.[SchDayThr] , sch.[SchDayFri] , sch.[SchDaySat] , sch.[ScheduleStartDate] , sch.[ScheduleEndDate] , sch.[Flags] , sch.[RecurrenceType] , sch.[State] , sub.[LastStatus] , rs.[ScheduleID] FROM [dbo].[Subscriptions] AS sub WITH (NOLOCK) LEFT JOIN [dbo].[Notifications] AS n WITH (NOLOCK) ON n.[SubscriptionID] = sub.[SubscriptionID] AND sub.[Report_OID] = n.[ReportID] LEFT JOIN [dbo].[ReportSchedule] AS rs WITH (NOLOCK) ON sub.[SubscriptionID] = rs.[SubscriptionID] LEFT JOIN subscription_schedule AS sch ON rs.[ScheduleID] = sch.[ScheduleID] ) SELECT rpt.[Path] , rpt.[ReportFolder] , rpt.[Name] , rpt.[URL_ReportFolder] , rpt.[URL_Report] , [URL_Report_Filtered] = rpt.URL_Report + '&rs:Command=Render&' + CONVERT(VARCHAR(2000), el.[Parameters]) , [UserName] = usr.[SimpleUserName] , el.[Status] , el.[TimeStart] , el.[RowCount] , el.[ByteCount] , el.[Format] , [Parameters] = REPLACE( REPLACE( REPLACE( REPLACE( REPLACE(CONVERT(NVARCHAR(MAX), el.[Parameters]) , '%20', ' ') , '%2F', '-') , '%3C', '<') , '%3E', '>') , '%3A', ':') , [TotalSeconds] = CONVERT(CHAR(8),DATEADD(ms, (el.[TimeDataRetrieval] + el.[TimeProcessing] + el.[TimeRendering]), 0), 108) , [TimeDataRetrieval] = CONVERT(CHAR(8),DATEADD(ms, el.[TimeDataRetrieval], 0), 108) , [TimeProcessing] = CONVERT(CHAR(8),DATEADD(ms, el.[TimeProcessing], 0), 108) , [TimeRendering] = CONVERT(CHAR(8),DATEADD(ms, el.[TimeRendering], 0), 108) , [SubscriptionOwner] = usc.[SimpleUserName] , [SubscriptionModifiedBy] = usm.[SimpleUserName] , [SubscriptionModifiedDate] = sub.[ModifiedDate] , sub.[SubscriptionID] , sub.[SubscriptionDescription] , sub.[ExtensionSettings] , sub.[EventType] , sub.[EmailSubject] , sub.[EmailTo] , sub.[EmailCc] , sub.[EmailBcc] , sub.[EmailComment] , sub.[EmailIncludeLink] , sub.[EmailRenderFormat] , sub.[EmailPriority] , sub.[DeliveryExtension] , [DeliveryExtensionImage] = CASE WHEN sub.[DeliveryExtension] = 'Report Server Email' THEN 'email' WHEN sub.[DeliveryExtension] = 'Report Server FileShare' THEN 'folder' ELSE sub.[DeliveryExtension] END , sub.[SubscriptionLastStatus] , sub.[StatusFail] , sub.[MatchData] , sub.[RunTime] , sub.[LastRunDate] , sub.[LastRunTime] , sub.[MinutesInterval] , sub.[DaysInterval] , sub.[WeeksInterval] , sub.[DaysOfWeek] , sub.[DaysOfMonth] , sub.[Month] , sub.[MonthlyWeek] , sub.[ScheduleName] , sub.[ScheduleDays] , sub.[SchDaySun] , sub.[SchDayMon] , sub.[SchDayTue] , sub.[SchDayWed] , sub.[SchDayThr] , sub.[SchDayFri] , sub.[SchDaySat] , sub.[ScheduleStartDate] , sub.[ScheduleEndDate] , sub.[Flags] , sub.[RecurrenceType] , sub.[State] , [EventStatus] = el.[Status] , [EventDateTime] = el.[TimeEnd] , sub.[LastStatus] , sub.[ScheduleID] FROM report_catalog AS rpt INNER JOIN report_subscription AS sub ON sub.[Report_OID] = rpt.[ItemID] LEFT JOIN [dbo].[ExecutionLog] AS el WITH (NOLOCK) ON el.[ReportID] = rpt.[ItemID] LEFT JOIN report_status AS rs ON el.[Status] = rs.[StatusName] LEFT JOIN report_users AS usr ON el.[UserName] = usr.[UserName] LEFT JOIN report_users AS usc ON sub.[OwnerID] = usc.[UserID] LEFT JOIN report_users AS usm ON sub.[ModifiedByID] = usm.[UserID] WHERE 1=1 AND (#StartDate IS NULL OR el.[TimeStart] >= #StartDate) AND (#EndDate IS NULL OR el.[TimeStart] <= #EndDate) AND (#ReportFolder IS NULL OR rpt.[ReportFolder] = #ReportFolder) AND (#ReportName IS NULL OR rpt.[ReportName] = #ReportName) AND (#LogStatus IS NULL OR el.[Status] = #LogStatus) AND (#StatusGroup IS NULL OR rs.[StatusGroup] = #StatusGroup) AND (#ServiceAccount IS NULL OR usr.[SimpleUserName] = #ServiceAccount) ORDER BY rpt.[Path] , el.[TimeStart] DESC
How to perform a dynamic pivot in T-SQL on a subset of columns
Software used: SQL Server 2014 Management Studio to query a standard 64-bit SQL Server. I'm trying to create a query that generates a set of patient assessment results across multiple patients / assessments, and to put the results of each assessment on one row. This would suggest the use of pivoting of some sort. Each assessment consists of a number of tests, each of which has a type, a name and a score. It is possible that we may want to add more tests to an assessment at some point, which would suggest the use of dynamic pivots. At the moment, my query essentially looks like this: SELECT TOP 20000 P.PatientId, P.LastName, P.FirstName, FORMAT(P.DateOfBirth, 'dd/MM/yyyy') as 'DateOfBirth', FORMAT(A.TreatmentDate, 'dd/MM/yyyy') as 'AssmentDate', A.TestType, A.TestName, A.TestScore FROM Patient P INNER JOIN Assessment A ON (A.PatientSerialNumber = P.PatientSerialNumber) INNER JOIN AssessmentHeader AH ON (AH.AssessmentSerialNumber = A.AssessmentSerialNumber AND AH.PatientSerialNumber = P.PatientSerialNumber) WHERE A.ValidEntryIndicator = 'Y' AND AH.ValidEntryIndicator = 'Y' ORDER BY P.PatientId, T.TreatmentDate My results essentially look like this (there are actually a lot more test types and names than shown here - these are just for illustration): PatientId LastName FirstName DateOfBirth AssmentDate TestType TestName TestScore AB1234 PATIENT Test 1/1/2000 1/1/2020 Renal Urgency 0 AB1234 PATIENT Test 1/1/2000 1/1/2020 Renal Retention 1 AB1234 PATIENT Test 1/1/2000 1/1/2020 GI Proctitis 2 AB1234 PATIENT Test 1/1/2000 1/1/2020 GI Diarrhea 3 AB1234 PATIENT Test 1/1/2000 6/6/2021 Renal Urgency 1 AB1234 PATIENT Test 1/1/2000 6/6/2021 Renal Retention 0 AB1234 PATIENT Test 1/1/2000 6/6/2021 GI Proctitis 1 AB1234 PATIENT Test 1/1/2000 6/6/2021 GI Diarrhea 2 YZ6789 PATIENT2 Test2 1/1/1999 7/7/2020 Renal Urgency 2 YZ6789 PATIENT2 Test2 1/1/1999 7/7/2020 Renal Retention 5 YZ6789 PATIENT2 Test2 1/1/1999 7/7/2020 GI Proctitis 3 YZ6789 PATIENT2 Test2 1/1/1999 7/7/2020 GI Diarrhea 1 YZ6789 PATIENT2 Test2 1/1/1999 6/7/2021 Renal Urgency 2 YZ6789 PATIENT2 Test2 1/1/1999 6/7/2021 Renal Retention 9 YZ6789 PATIENT2 Test2 1/1/1999 6/7/2021 GI Proctitis 4 YZ6789 PATIENT2 Test2 1/1/1999 6/7/2021 GI Diarrhea 5 What I would like is this: PatientId LastName FirstName DateOfBirth AssmentDate Renal-Urgency Renal-Retention GI-Proctitis GI-Diarrhea AB1234 PATIENT Test 1/1/2000 1/1/2020 0 1 2 3 AB1234 PATIENT Test 1/1/2000 6/6/2021 1 0 1 2 YZ6789 PATIENT2 Test2 1/1/1999 7/7/2020 2 5 3 1 YZ6789 PATIENT2 Test2 1/1/1999 6/7/2021 2 9 4 5 I've tried to follow various online resources and SO question/answers (this one looked the most promising), but I just can't seem to get the methods shown in these to work with my query (frustratingly) Can anyone help me out?
So you can use the technique shown at the linked answer, you just need to extend it to handle multiple key-columns and multiple pivot-source columns: CREATE TABLE #Table ( -- key columns PatientId Varchar(8), LastName VarChar(32), FirstName Varchar(32), DateOfBirth DateTime, AssmentDate DateTime, -- pivot-source columns TestType Varchar(20), TestName Varchar(20), -- value column TestScore INT ) go INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'Renal', 'Urgency', '0'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'Renal', 'Retention', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'GI', 'Proctitis', '2'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'GI', 'Diarrhea', '3'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'Renal', 'Urgency', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'Renal', 'Retention', '0'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'GI', 'Proctitis', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'GI', 'Diarrhea', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'Renal', 'Urgency', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'Renal', 'Retention', '5'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2 ', '1/1/1999', '7/7/2020', 'GI', 'Proctitis', '3'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'GI', 'Diarrhea', '1'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'Renal', 'Urgency', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'Renal ', 'Retention', '9'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'GI', 'Proctitis', '4'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'GI', 'Diarrhea', '5'); go DECLARE #cols NVARCHAR(2000) DECLARE #query NVARCHAR(4000) SELECT #cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' + t.TestType + '-' + t.TestName FROM #Table AS t FOR XML PATH('') ), 1, 2, '') + ']' SELECT #cols SET #query = N'SELECT PatientId, LastName, FirstName, DateOfBirth, AssmentDate, ' + #cols +' FROM (SELECT PatientId, LastName, FirstName, DateOfBirth, AssmentDate, ' +' TestType + ''-'' + TestName AS ColName, TestScore FROM #Table AS t1) p PIVOT (MAX([TestScore]) FOR ColName IN ( '+ #cols +' )) AS pvt;' PRINT(#query) EXECUTE(#query) DROP TABLE #Table GO In your case, you would use the query you have in your question to load #Table. I had to guess about the length of the Varchar(..) columns, so you will need to check and correct them.
Pivot is based on column values so the answer depends on what values are there in the columns. CREATE TABLE #Table ( -- key columns PatientId Varchar(8), LastName VarChar(32), FirstName Varchar(32), DateOfBirth DateTime, AssesmentDate DateTime, -- pivot-source columns TestType Varchar(20), TestName Varchar(20), -- value column TestScore INT ) go INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'Renal', 'Urgency', '0'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'Renal', 'Retention', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'GI', 'Proctitis', '2'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '1/1/2020', 'GI', 'Diarrhea', '3'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'Renal', 'Urgency', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'Renal', 'Retention', '0'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'GI', 'Proctitis', '1'); INSERT INTO #Table Values('AB1234', 'PATIENT', 'Test', '1/1/2000', '6/6/2021', 'GI', 'Diarrhea', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'Renal', 'Urgency', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'Renal', 'Retention', '5'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2 ', '1/1/1999', '7/7/2020', 'GI', 'Proctitis', '3'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '7/7/2020', 'GI', 'Diarrhea', '1'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'Renal', 'Urgency', '2'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'Renal', 'Retention', '9'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'GI', 'Proctitis', '4'); INSERT INTO #Table Values('YZ6789', 'PATIENT2', 'Test2', '1/1/1999', '6/7/2021', 'GI', 'Diarrhea', '5'); go --select * from #Table DECLARE #SQL AS VARCHAR(MAX) , #cols_ AS VARCHAR(MAX) --Making the column list dynamically SELECT #cols_ = STUFF((SELECT DISTINCT ', '+QUOTENAME( C.TestType +'-'+C.TestName) FROM #Table C FOR XML PATH('')), 1, 1, '') --preparing PIVOT query dynamically. select #cols_ --View the columns SET #SQL = ' SELECT pivoted.PatientId ,pivoted.FirstName ,pivoted.LastName ,pivoted.DateOfBirth ,pivoted.AssesmentDate ,'+#cols_+' FROM ( SELECT PatientId , LastName , FirstName, DateOfBirth, AssesmentDate, TestType+''-''+ TestName as [PivotedCol], TestScore FROM #Table ) AS cp PIVOT ( MAX([CP].[TestScore]) FOR [CP].[PivotedCol] IN (' + #cols_ + ') ) AS pivoted; ' ; PRINT(#SQL) EXECUTE(#SQL) DROP TABLE #Table
Remove transformation is not working for a column
I am trying out a scenario where tables of two databases in MySQL are synchronized and in some places, columns are transformed. I have a perticular case where every column of DB1 table while insertion, will be synchronized (a new row will be inserted in DB2) but for updating that row, a specific column will have no effect on DB2 table (every other column will be updated). I am trying to achieve this by 'remove transformation' (one of the transformation types). But my remove transformation is not working. Other transformations are working fine. May be I have missed a thing. A little help will be much appreciated. DB1: records_new Table: employee CREATE TABLE `employee` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `title` varchar(11) DEFAULT 'Mr.', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci DB2: records_new_replica Table: employee CREATE TABLE `employee` ( `id` bigint(20) NOT NULL, `emp_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `title` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `designation` varchar(100) DEFAULT NULL, `name` varchar(100) DEFAULT NULL, `time` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ////////////////////////////////////////////////////////sym tables////////////////////////////////////////////////////////// sym_node_group INSERT INTO records.sym_node_group (node_group_id, description, create_time, last_update_by, last_update_time) VALUES('records', NULL, NULL, NULL, NULL); INSERT INTO records.sym_node_group (node_group_id, description, create_time, last_update_by, last_update_time) VALUES('records-replica', NULL, NULL, NULL, NULL); sym_node INSERT INTO records.sym_node (node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type) VALUES('000', 'records', '000', 1, 'http://localhost:31415/sync/records-000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, NULL, 'server', NULL); INSERT INTO records.sym_node (node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type) VALUES('2000', 'records-replica', '2000', 1, 'http://DESKTOP-KSP9CJD:31415/sync/records-replica-1000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, '000', 'server', NULL); sym_router INSERT INTO records.sym_router (router_id, target_catalog_name, target_schema_name, target_table_name, source_node_group_id, target_node_group_id, router_type, router_expression, sync_on_update, sync_on_insert, sync_on_delete, use_source_catalog_schema, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-new', '', '', '', 'records', 'records-replica', 'default', '', 1, 1, 0, 1, '2019-10-30 09:40:25', NULL, '2019-10-30 09:40:25', ''); sym_trigger INSERT INTO records.sym_trigger (trigger_id, source_catalog_name, source_schema_name, source_table_name, channel_id, reload_channel_id, sync_on_update, sync_on_insert, sync_on_delete, sync_on_incoming_batch, name_for_update_trigger, name_for_insert_trigger, name_for_delete_trigger, sync_on_update_condition, sync_on_insert_condition, sync_on_delete_condition, custom_before_update_text, custom_before_insert_text, custom_before_delete_text, custom_on_update_text, custom_on_insert_text, custom_on_delete_text, external_select, tx_id_expression, channel_expression, excluded_column_names, included_column_names, sync_key_names, use_stream_lobs, use_capture_lobs, use_capture_old_data, use_handle_key_updates, stream_row, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-trig_new', 'records_new', '', 'employee', 'employee', 'reload', 1, 1, 0, 0, NULL, NULL, NULL, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 1, 1, 0, '2019-10-30 09:38:56', NULL, '2019-10-30 09:38:56', ''); sym_trigger_router INSERT INTO records.sym_trigger_router (trigger_id, router_id, enabled, initial_load_order, initial_load_select, initial_load_delete_stmt, ping_back_enabled, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-trig_new', 'emp-2-emp-new', 1, 1, '', '', 0, '2019-10-30 09:41:31', NULL, '2019-10-30 09:41:31', ''); sym_transform_table INSERT INTO records.sym_transform_table (transform_id, source_node_group_id, target_node_group_id, transform_point, source_catalog_name, source_schema_name, source_table_name, target_catalog_name, target_schema_name, target_table_name, update_first, update_action, delete_action, transform_order, column_policy, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-new', 'records', 'records-replica', 'LOAD', 'records_new', NULL, 'employee', 'records_new_replica', NULL, 'employee', 0, 'UPDATE_COL', 'NONE', 1, 'IMPLIED', '2019-10-30 11:38:22', NULL, '2019-10-30 11:38:22', ''); sym_transform_column INSERT INTO records.sym_transform_column (transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-new', '*', 'emp_name', 'name', 0, 'copy', '', 1, '2019-10-30 11:38:49', NULL, '2019-10-30 11:38:49', ''); INSERT INTO records.sym_transform_column (transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-new', '*', 'time', NULL, 0, 'lookup', 'select UNIX_TIMESTAMP()', 1, '2019-10-31 10:01:02', NULL, '2019-10-31 10:01:02', ''); INSERT INTO records.sym_transform_column (transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description) VALUES('emp-2-emp-new', 'U', 'title', 'title', 0, 'remove', '', 1, '2019-11-06 13:20:21', '', '2019-11-06 13:20:21', ''); Thanks in advance.:)
I wanted to delete this question. But i figured that may be...if someone stumbled upon symmetricds and after reading the user guide..missed a corner and that became a doom for him...only for those...here it goes: In the guide, when describing fields of sym_router table, it is stated about the Use Source Catalog/Schema field that If set then the source catalog and source schema are sent to the target to be used to find the target table. and in appendix/ROUTER it is stated about USE_SOURCE_CATALOG_SCHEMA that, Whether or not to assume that the target catalog/schema name should be the same as the source catalog/schema name. The target catalog or schema name will still override if not blank. Now lets see what might override those target variables. In Transform section, they have stated the following: Source Catalog Name of the catalog of the configured source table. This should only be set if Use Source Catalog/Schema or Target Catalog are set on the Router. Source Schema Name of the schema for the configured source table. This should only be set if Use Source Catalog/Schema or Target Schema are set on the Router. So, the resolution is, when I have set the source_catalog_name in sym_transform_table, then I have to set the use_source_catalog_schema in sym_router table and as my tables which I intended to sync is not in the default catalog then I have to explicitly set the other two columns e.g. target_catalog_name and target_table_name in sym_transform_table. tl;dr, set the use_source_catalog_schema in table sym_router to 1 if source_catalog_name is set in the sym_transform_table for transformation and another thing...read the guide.it's brief but it's our only friend.
CTE Code just grabbing anchor not making recursion
query is not making the recursion, it only fetches the anchor part (the ids where parent id is null). Can anyone help me spot my mistake? I have tried a lot things but I am always retrieving the same number of rows, the IDS with no parent ids. WITH EmpTree AS ( SELECT e.DWH_Dim_TFS_File_DWH_FileParent_Guid ,e.DWH_Dim_TFS_File_DWH_File_Guid ,1 AS Depth ,File_Name_String = CAST(CAST(e.File_Name AS BINARY (100)) AS VARBINARY(8000)) FROM [dbo].[Hierarchy_Luis] AS e WHERE e.DWH_Dim_TFS_File_DWH_FileParent_Guid IS NULL UNION ALL SELECT e.DWH_Dim_TFS_File_DWH_FileParent_Guid ,e.DWH_Dim_TFS_File_DWH_File_Guid ,p.Depth + 1 AS Depth ,File_Name_String = CAST(CONCAT ( p.File_Name_String ,CAST(e.File_Name AS BINARY (100)) ) AS VARBINARY(8000)) FROM [dbo].[Hierarchy_Luis] AS e JOIN EmpTree AS p ON e.DWH_Dim_TFS_File_DWH_FileParent_Guid = p.DWH_Dim_TFS_File_DWH_File_Guid ) SELECT p.DWH_Dim_TFS_File_DWH_File_Guid ,p.Depth ,Level01 = CAST(SUBSTRING(p.File_Name_String, 1, 100) AS NVARCHAR(100)) ,Level02 = CAST(SUBSTRING(p.File_Name_String, 101, 100) AS NVARCHAR(100)) ,Level03 = CAST(SUBSTRING(p.File_Name_String, 201, 100) AS NVARCHAR(100)) ,Level04 = CAST(SUBSTRING(p.File_Name_String, 301, 100) AS NVARCHAR(100)) ,Level05 = CAST(SUBSTRING(p.File_Name_String, 401, 100) AS NVARCHAR(100)) ,Level07 = CAST(SUBSTRING(p.File_Name_String, 501, 100) AS NVARCHAR(100)) ,Level08 = CAST(SUBSTRING(p.File_Name_String, 601, 100) AS NVARCHAR(100)) ,Level09 = CAST(SUBSTRING(p.File_Name_String, 701, 100) AS NVARCHAR(100)) ,Level10 = CAST(SUBSTRING(p.File_Name_String, 801, 100) AS NVARCHAR(100)) ,Level11 = CAST(SUBSTRING(p.File_Name_String, 901, 100) AS NVARCHAR(100)) ,Level12 = CAST(SUBSTRING(p.File_Name_String, 1001, 100) AS NVARCHAR(100)) ,Level13 = CAST(SUBSTRING(p.File_Name_String, 1101, 100) AS NVARCHAR(100)) ,Level14 = CAST(SUBSTRING(p.File_Name_String, 1201, 100) AS NVARCHAR(100)) ,Level15 = CAST(SUBSTRING(p.File_Name_String, 1301, 100) AS NVARCHAR(100)) ,Level16 = CAST(SUBSTRING(p.File_Name_String, 1401, 100) AS NVARCHAR(100)) ,Level17 = CAST(SUBSTRING(p.File_Name_String, 1501, 100) AS NVARCHAR(100)) ,Level18 = CAST(SUBSTRING(p.File_Name_String, 1601, 100) AS NVARCHAR(100)) ,Level19 = CAST(SUBSTRING(p.File_Name_String, 1701, 100) AS NVARCHAR(100)) ,Level20 = CAST(SUBSTRING(p.File_Name_String, 1801, 100) AS NVARCHAR(100)) ,Level21 = CAST(SUBSTRING(p.File_Name_String, 1901, 100) AS NVARCHAR(100)) ,Level22 = CAST(SUBSTRING(p.File_Name_String, 2001, 100) AS NVARCHAR(100)) ,Level23 = CAST(SUBSTRING(p.File_Name_String, 2101, 100) AS NVARCHAR(100)) ,Level24 = CAST(SUBSTRING(p.File_Name_String, 2201, 100) AS NVARCHAR(100)) ,Level25 = CAST(SUBSTRING(p.File_Name_String, 2301, 100) AS NVARCHAR(100)) ,Level26 = CAST(SUBSTRING(p.File_Name_String, 2401, 100) AS NVARCHAR(100)) ,Level27 = CAST(SUBSTRING(p.File_Name_String, 2501, 100) AS NVARCHAR(100)) FROM EmpTree p You can see in the link the two columns data types where the recursion is being made, it is a nvarchar(256) Thanks a lot, I know it must be something quite basic, but I can not find out. Sample DATA DWH_Dim_TFS_File_DWH_FileParent_GUID DWH_Dim_TFS_File_DWH_File_GUID File_Name 114087616 114087617 ot_de 114087616 114087618 ot_de 114087593 114087619 _proj 11407441 11408762 I_EXP 114087593 114087620 arm\ 114087620 114087621 e\ 114087621 114087622 ot_de 114087621 114087623 ot_de 114087593 114087624 c\ 114087624 114087625 ot_de 114087624 114087626 ot_de 114087593 114087627 3s896 114087593 114087628 kefil 114087593 114087629 adme. 11408762 11408763 B_PTS 114087593 114087630 mdk\ 114087630 114087631 ot_de 114087630 114087632 ot_de 114087593 114087633 urcer 114087633 114087634 ot_de 114087633 114087635 ot_de 114087593 114087636 artup 114087593 114087637 artup 114087593 114087638 artup 114087593 114087639 artup 11408763 11408764 B_PTS 114087593 114087640 artup 114087302 114087641 ot_et 114087641 114087642 _conf 114087641 114087643 ot_et 114087641 114087644 ot_et 114087641 114087645 ot_et 114087641 114087646 ot_et 114087641 114087647 ot_et 114087641 114087648 s\ 114087648 114087649 csimp 11408763 11408765 B_PTS 114087648 114087650 cspro 114087648 114087651 dtbui 114087648 114087652 dtpro 114087648 114087653 rojec 114087648 114087654 ettin 114087654 114087655 g.ecl 114087648 114087656 cros. 114087648 114087657 rget_ 114087641 114087658 dered 114087658 114087659 ot_et 11408763 11408766 cessW
This is the answer based on comments earlier: The solution was that he did not have any match where they were null - He had to match them in first select. WITH EmpTree AS ( SELECT e.DWH_Dim_TFS_File_DWH_FileParent_Guid ,e.DWH_Dim_TFS_File_DWH_File_Guid ,1 AS Depth ,File_Name_String = CAST(CAST(e.File_Name AS BINARY (100)) AS VARBINARY(8000)) FROM [dbo].[Hierarchy_Luis] AS e WHERE e.DWH_Dim_TFS_File_DWH_FileParent_Guid = e.DWH_Dim_TFS_File_DWH_File_Guid UNION ALL SELECT e.DWH_Dim_TFS_File_DWH_FileParent_Guid ,e.DWH_Dim_TFS_File_DWH_File_Guid ,p.Depth + 1 AS Depth ,File_Name_String = CAST(CONCAT ( p.File_Name_String ,CAST(e.File_Name AS BINARY (100)) ) AS VARBINARY(8000)) FROM [dbo].[Hierarchy_Luis] AS e JOIN EmpTree AS p ON e.DWH_Dim_TFS_File_DWH_FileParent_Guid = p.DWH_Dim_TFS_File_DWH_File_Guid ) SELECT p.DWH_Dim_TFS_File_DWH_File_Guid ,p.Depth ,Level01 = CAST(SUBSTRING(p.File_Name_String, 1, 100) AS NVARCHAR(100)) ,Level02 = CAST(SUBSTRING(p.File_Name_String, 101, 100) AS NVARCHAR(100)) ,Level03 = CAST(SUBSTRING(p.File_Name_String, 201, 100) AS NVARCHAR(100)) ,Level04 = CAST(SUBSTRING(p.File_Name_String, 301, 100) AS NVARCHAR(100)) ,Level05 = CAST(SUBSTRING(p.File_Name_String, 401, 100) AS NVARCHAR(100)) ,Level07 = CAST(SUBSTRING(p.File_Name_String, 501, 100) AS NVARCHAR(100)) ,Level08 = CAST(SUBSTRING(p.File_Name_String, 601, 100) AS NVARCHAR(100)) ,Level09 = CAST(SUBSTRING(p.File_Name_String, 701, 100) AS NVARCHAR(100)) ,Level10 = CAST(SUBSTRING(p.File_Name_String, 801, 100) AS NVARCHAR(100)) ,Level11 = CAST(SUBSTRING(p.File_Name_String, 901, 100) AS NVARCHAR(100)) ,Level12 = CAST(SUBSTRING(p.File_Name_String, 1001, 100) AS NVARCHAR(100)) ,Level13 = CAST(SUBSTRING(p.File_Name_String, 1101, 100) AS NVARCHAR(100)) ,Level14 = CAST(SUBSTRING(p.File_Name_String, 1201, 100) AS NVARCHAR(100)) ,Level15 = CAST(SUBSTRING(p.File_Name_String, 1301, 100) AS NVARCHAR(100)) ,Level16 = CAST(SUBSTRING(p.File_Name_String, 1401, 100) AS NVARCHAR(100)) ,Level17 = CAST(SUBSTRING(p.File_Name_String, 1501, 100) AS NVARCHAR(100)) ,Level18 = CAST(SUBSTRING(p.File_Name_String, 1601, 100) AS NVARCHAR(100)) ,Level19 = CAST(SUBSTRING(p.File_Name_String, 1701, 100) AS NVARCHAR(100)) ,Level20 = CAST(SUBSTRING(p.File_Name_String, 1801, 100) AS NVARCHAR(100)) ,Level21 = CAST(SUBSTRING(p.File_Name_String, 1901, 100) AS NVARCHAR(100)) ,Level22 = CAST(SUBSTRING(p.File_Name_String, 2001, 100) AS NVARCHAR(100)) ,Level23 = CAST(SUBSTRING(p.File_Name_String, 2101, 100) AS NVARCHAR(100)) ,Level24 = CAST(SUBSTRING(p.File_Name_String, 2201, 100) AS NVARCHAR(100)) ,Level25 = CAST(SUBSTRING(p.File_Name_String, 2301, 100) AS NVARCHAR(100)) ,Level26 = CAST(SUBSTRING(p.File_Name_String, 2401, 100) AS NVARCHAR(100)) ,Level27 = CAST(SUBSTRING(p.File_Name_String, 2501, 100) AS NVARCHAR(100)) FROM EmpTree p