I have a query as follows
SELECT
FGB.TEMPLATE_DETAILS_REF, FGB.TEMPLATE_STRUCTURE_REF, FGB.DFEE_ELEMENT,
CASE
WHEN Condition = 'A' THEN SUM(FGS.Weighted) END AS CondA,
CASE
WHEN Condition = 'B' THEN SUM(FGS.Weighted) END AS CondB,
CASE
WHEN Condition = 'C' THEN SUM(FGS.Weighted) END AS CondC,
CASE
WHEN Condition = 'D' THEN SUM(FGS.Weighted) END AS CondD
FROM FGBlockSummary AS FGB INNER JOIN
FGSurveyItem AS FGS ON FGB.TEMPLATE_DETAILS_REF = FGS.TEMPLATE_DETAILS_REF AND FGB.TEMPLATE_STRUCTURE_REF = FGS.TEMPLATE_STRUCTURE_REF AND
FGB.DFEE_ELEMENT = FGS.DFEE_ELEMENT
GROUP BY FGB.TEMPLATE_DETAILS_REF, FGB.TEMPLATE_STRUCTURE_REF, FGB.DFEE_ELEMENT, FGS.Condition
which produces results as follows:
16 109 Ceilings NULL 14101.47 NULL NULL
16 109 Ceilings NULL NULL 227.68 NULL
How can I amalgamate the results into a single row eg
16 109 Ceilings NULL 14101.47 227.68 NULL
Thanks
Is this what you're looking for?
I moved the SUM outside of the CASEs and eliminated FGS.Condition from the GROUP BY. It'll have the side-effect of changing your NULL values to '0', but that might be tolerable?
SELECT
FGB.TEMPLATE_DETAILS_REF
,FGB.TEMPLATE_STRUCTURE_REF
,FGB.DFEE_ELEMENT
,CondA = SUM(
CASE
WHEN FGS.Condition = 'A' THEN FGS.Weighted
ELSE 0
END)
,CondB = SUM(
CASE
WHEN FGS.Condition = 'B' THEN FGS.Weighted
ELSE 0
END)
,CondC = SUM(
CASE
WHEN FGS.Condition = 'C' THEN FGS.Weighted
ELSE 0
END)
,CondD = SUM(
CASE
WHEN FGS.Condition = 'D' THEN FGS.Weighted
ELSE 0
END)
FROM
FGBlockSummary AS FGB
INNER JOIN
FGSurveyItem AS FGS
ON
FGB.TEMPLATE_DETAILS_REF = FGS.TEMPLATE_DETAILS_REF
AND FGB.TEMPLATE_STRUCTURE_REF = FGS.TEMPLATE_STRUCTURE_REF
AND FGB.DFEE_ELEMENT = FGS.DFEE_ELEMENT
GROUP BY
FGB.TEMPLATE_DETAILS_REF
,FGB.TEMPLATE_STRUCTURE_REF
,FGB.DFEE_ELEMENT;
Related
Needs to create view with below columns. Need to understand how to create view using with clause inside the query.
create
or replace view TEST_RRX.DW_RRX.V_SIL_RRX_PTS_BusinessLocation_Dim(
--ROW_WID,
--ADDRESS_TYPE,
BUSN_LOC_NAME,
BUSN_LOC_NUM,
BUSN_LOC_TYPE,
ST_ADDRESS1,
ST_ADDRESS2,
CITY_NAME,
POSTAL_CODE,
STATE_CODE,
COUNTRY_CODE,
ACTIVE_FLG,
CREATED_BY_WID,
CHANGED_BY_WID,
CREATED_ON_DT,
CHANGED_ON_DT,
AUX1_CHANGED_ON_DT,
AUX2_CHANGED_ON_DT,
AUX3_CHANGED_ON_DT,
AUX4_CHANGED_ON_DT,
SRC_EFF_FROM_DT,
SRC_EFF_TO_DT,
EFFECTIVE_FROM_DT,
EFFECTIVE_TO_DT,
DELETE_FLG,
CURRENT_FLG,
W_INSERT_DT,
W_UPDATE_DT,
DATASOURCE_NUM_ID,
--ETL_PROC_WID,
INTEGRATION_ID,
--TENANT_ID,
--X_CUSTOM,
--GEO_COUNTRY_WID,
--GEO_WID,
UPD_FLG
) as WITH CODE AS (
SELECT
W_CODE_D.MASTER_CODE AS MASTER_CODE,
W_CODE_D.MASTER_VALUE AS MASTER_VALUE,
W_CODE_D.SOURCE_CODE AS SOURCE_CODE,
W_CODE_D.DATASOURCE_NUM_ID AS DATASOURCE_NUM_ID,
W_CODE_D.SOURCE_CODE_1 as SOURCE_CODE_1,
W_CODE_D.SOURCE_CODE_2 as SOURCE_CODE_2,
W_CODE_D.SOURCE_NAME_1 as SOURCE_NAME_1,
W_CODE_D.CATEGORY
FROM
W_CODE_D
WHERE
W_CODE_D.LANGUAGE_CODE = 'E'
),
USER_TAB as (
SELECT
LOOKUP_TABLE.ROW_WID as ROW_WID,
LOOKUP_TABLE.DATASOURCE_NUM_ID as DATASOURCE_NUM_ID,
LOOKUP_TABLE.INTEGRATION_ID as INTEGRATION_ID,
LOOKUP_TABLE.EFFECTIVE_FROM_DT as EFFECTIVE_FROM_DT,
LOOKUP_TABLE.EFFECTIVE_TO_DT as EFFECTIVE_TO_DT
FROM
DW_RRX.W_USER_D LOOKUP_TABLE
),
BUSN_LOCATION as (
SELECT
sq.BUSN_LOC_NAME,
sq.BUSN_LOC_NUM,
sq.BUSN_LOC_TYPE,
sq.ST_ADDRESS1,
sq.ST_ADDRESS2,
case when CITY.MASTER_VALUE is null then (
case when sq.CITY_NAME is null
OR LENGTH(sq.CITY_NAME) = 0
OR REGEXP_INSTR(sq.CITY_NAME, ' ')> 0 then 'Unspecified' else sq.CITY_NAME end
) else CITY.MASTER_VALUE end as city_name,
sq.POSTAL_CODE,
case when STATE.MASTER_CODE is null then (
case when sq.STATE_CODE is null
OR LENGTH(sq.STATE_CODE) = 0
OR REGEXP_INSTR(sq.STATE_CODE, ' ')> 0 then 'Unspecified' else sq.STATE_CODE end
) else STATE.MASTER_CODE end as STATE_CODE,
case when COUNTRY.MASTER_CODE is null then (
case when sq.COUNTRY_CODE is null
OR LENGTH(sq.COUNTRY_CODE) = 0
OR REGEXP_INSTR(sq.COUNTRY_CODE, ' ')> 0 then 'Unspecified' else sq.COUNTRY_CODE end
) else COUNTRY.MASTER_VALUE end as COUNTRY_CODE,
'Y' as ACTIVE_FLG,
CREATED_BY.ROW_WID AS CREATED_BY_WID,
CHANGED_BY.ROW_WID AS CREATED_BY_WID,
sq.AUX1_CHANGED_ON_DT,
sq.AUX2_CHANGED_ON_DT,
sq.AUX3_CHANGED_ON_DT,
sq.AUX4_CHANGED_ON_DT,
sq.SRC_EFF_FROM_DT,
sq.SRC_EFF_TO_DT,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as EFFECTIVE_FROM_DT,
TO_DATE('01013714', 'DDMMYYYY') as EFFECTIVE_TO_DT,
'N' As DELETE_FLG,
'Y' AS CURRENT_FLG,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as W_INSERT_DT,
W_BUSN_LOCATION_D.W_UPDATE_DT as current_date,
sq.DATASOURCE_NUM_ID,
--sq.ETL_PROC_WID,
sq.INTEGRATION_ID,
CASE WHEN (
SELECT
ETL_PROC_WID
FROM
TEST_RRX.DW_RRX.W_PARAM_G
WHERE
ROW_WID = 1
) = W_BUSN_LOCATION_D.ETL_PROC_WID THEN 'X' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NULL THEN 'I' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NOT NULL
AND (
sq.CHANGED_ON_DT <> W_BUSN_LOCATION_D.CHANGED_ON_DT
OR sq.AUX1_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX1_CHANGED_ON_DT
OR sq.AUX2_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX2_CHANGED_ON_DT
OR sq.AUX3_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX3_CHANGED_ON_DT
OR sq.AUX4_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX4_CHANGED_ON_DT
) THEN 'U' END as UPD_FLG
FROM
DW_RRX.W_BUSN_LOCATION_DS sq
LEFT OUTER JOIN CODE COUNTRY ON COUNTRY.SOURCE_CODE = sq.country_code
AND COUNTRY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND COUNTRY.CATEGORY = 'COUNTRY'
LEFT OUTER JOIN CODE CITY ON CITY.SOURCE_CODE_1 = sq.country_code
AND CITY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND CITY.SOURCE_CODE_2 = sq.STATE_CODE
AND CITY.SOURCE_NAME_1 = sq.CITY_NAME
AND CITY.CATEGORY = 'CITY'
LEFT OUTER JOIN CODE STATE ON STATE.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND STATE.CATEGORY = 'STATE'
LEFT OUTER JOIN USER_TAB CREATED_BY ON sq.DATASOURCE_NUM_ID = CREATED_BY.DATASOURCE_NUM_ID
AND CREATED_BY.INTEGRATION_ID = sq.CREATED_BY_ID
and CREATED_BY.EFFECTIVE_FROM_DT <= sq.CREATED_ON_DT
and CREATED_BY.EFFECTIVE_TO_DT >= sq.CREATED_ON_DT
LEFT OUTER JOIN USER_TAB CHANGED_BY ON sq.DATASOURCE_NUM_ID = CHANGED_BY.DATASOURCE_NUM_ID
AND CHANGED_BY.INTEGRATION_ID = sq.CHANGED_BY_ID
and CHANGED_BY.EFFECTIVE_FROM_DT <= sq.CHANGED_ON_DT
and CHANGED_BY.EFFECTIVE_TO_DT >= sq.CHANGED_ON_DT
LEFT OUTER JOIN W_BUSN_LOCATION_D ON sq.INTEGRATION_ID = W_BUSN_LOCATION_D.INTEGRATION_ID
AND sq.DATASOURCE_NUM_ID = W_BUSN_LOCATION_D.DATASOURCE_NUM_ID
)
SELECT
*
FROM
BUSN_LOCATION
WHERE
UPD_FLG <> 'X'
Getting SQL compilation error: Invalid column definition list
Needs to create view with above columns
Inside the JOIN (BB_VENDASDOCUMENTOS VD), I need to choose if VD.ENTRADASAIDA will be 'S' or 'E', what I actually need is, if there is at least one BB_VENDASDOCUMENTOS where ENTRADASAIDA = 'S', use 'S', else 'N'
I've tried to do a CASE WHEN counting the numer of VD.ENTRADASAIDA = 'S', if there is more then 0, It will use 'S', else 'N', but I'm getting an error that and aggregate cannot appear in an ON clause...
SELECT
CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
FROM BB_PNRACCOUNTINGS ACC1
JOIN BB_VENDASDOCUMENTOS VD
ON ( VD.ACCOUNTING = ACC1.HANDLE
AND VD.ENTRADASAIDA = CASE WHEN count(case when VD.ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S' ELSE 'E' END
AND VD.PESSOA = ACC1.BB_CLIENTE
AND ( ( VD.CANCELADO = 'N' ) OR (VD.CANCELADO IS NULL) ) )
LEFT JOIN BB_CLIENTECC CENTROCUSTO
ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
WHERE CENTROCUSTO.DESCRICAO IS NOT NULL
You will need to scan the table twice. Once to mark each group with a S or E and then to gather only the records that match the condition. I would do this by joining on a subquery and then join again on the condition. I am not sure the syntax below is 100% correct, however, the basic concept is there.
;WITH BB_VENDASDOCUMENTOSCalc AS
(
SELECT ACCOUNTING,PESSOA,
ENTRADASAIDACalc = count(case when ENTRADASAIDA = 'S' THEN 1 ELSE NULL END ) > 0 THEN 'S' ELSE 'E' END
FROM
BB_VENDASDOCUMENTOS
WHERE
(CANCELADO='N' OR CANCELADO IS NULL)
GROUP BY
ACCOUNTING,
PESSOA
)
SELECT
CASE WHEN CENTROCUSTO.DESCRICAO IS NOT NULL THEN CENTROCUSTO.DESCRICAO + '|' ELSE '' END AS [text()]
FROM BB_PNRACCOUNTINGS ACC1
JOIN BB_VENDASDOCUMENTOSCalc VD1 ON VD1.ACCOUNTING = ACC1.HANDLE AND VD1.PESSOA = ACC1.BB_CLIENTE
JOIN BB_VENDASDOCUMENTO VD ON VD.ACCOUNTING = ACC1.HANDLE AND VD.PESSOA = ACC1.BB_CLIENTE AND VD.ENTRADASAIDA = VD1.ENTRADASAIDACalc
LEFT JOIN BB_CLIENTECC CENTROCUSTO
ON (CENTROCUSTO.Handle = VD.CENTRODECUSTO)
WHERE CENTROCUSTO.DESCRICAO IS NOT NULL
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
My stored procedure is taking around 1 minute 45 seconds, how can I optimize it? I tried couple of things like creating temp table before doing the insert.
I have Estimated Execution Plan but I don't know how to upload it.
This is part of my stored procedure which is taking longer time and Query Cost is 53%.
SELECT Distinct
BackupCTE.[InstanceName]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.EnvironmentType = 0 THEN '-1' Else CONVERT(VARCHAR,BackupCTE.EnvironmentType) END AS EnvironmentType
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.InstanceStatus = 0 THEN '-1' Else CONVERT(VARCHAR,BackupCTE.InstanceStatus) END AS [InstanceStatus]
,BackupCTE.[BackupShare]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.DatabaseOwner = 0 THEN '-1'
WHEN ISNULL(BackupCTE.IsMirroringEnabled,0) = 0 AND BackupCTE.DatabaseOwner NOT IN ('SA') AND BackupCTE.DatabaseStatus = 'Normal' AND BackupCTE.DatabaseReadOnly = 0
AND ISNULL(BackupCTE.IsDatabaseSnapshot,0) = 0 THEN '0'
ELSE '1' END AS DatabaseOwner
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.DBRecoveryModel = 0 THEN '-1'
WHEN BackupCTE.DatabaseStatus = 'Normal' AND BackupCTE.DatabaseName NOT IN ('master', 'msdb', 'IHC_DBA','distribution','ReportServerTempDB','NavicareReporting','ReportServer') AND
BackupCTE.RecoveryModel NOT IN ('Full','BulkLogged') THEN '0'
ELSE '1'
END AS [DBRecoveryModel]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.AutoShrink = 0 THEN '-1'
ELSE CONVERT(VARCHAR, BackupCTE.[AutoShrink]) END AS [AutoShrink]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.AutoClose = 0 THEN '-1' Else CONVERT(VARCHAR,BackupCTE.[AutoClose]) END AS [AutoClose]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.BackupCompression = 0 THEN '-1'
WHEN BackupCTE.[BackupCompression] = 0 THEN '0'
Else '1' END AS [BackupCompression]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.XPCmdShell = 0 THEN '-1'
WHEN CONVERT(VARCHAR,BackupCTE.[XPCmdShell]) = 0 THEN '1'
Else '0' END AS [XPCmdShell]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.EncryptionEnabled = 0 THEN '-1' Else CONVERT(VARCHAR,BackupCTE.[EncryptionEnabled]) END AS [EncryptionEnabled]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.IsIdera = 0 THEN '-1' Else CONVERT(VARCHAR,BackupCTE.[IsIdera]) END AS [IsIdera]
,[HoursRetentionShare]
,[HoursSinceLastFullBackup]
,[HoursSinceLastDiffBackup]
,[HoursSinceLastLogBackup]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.ExceededBkpTimeFrame = 0 THEN '-1' Else BackupCTE.ExceededBkpTimeFrame
END AS ExceededBkpTimeFrame
,BackupType
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[Primary] = 0 THEN '-1' Else BackupCTE.[Primary] END AS [Primary]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[Secondary] = 0 THEN '-1' Else BackupCTE.[Secondary] END AS [Secondary]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[LockPages] = 0 THEN '-1'
Else CONVERT(varchar,BackupCTE.[LockPages]) END AS [LockPages]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[SADisabled] = 0 THEN '-1'
WHEN CONVERT(varchar,BackupCTE.[SADisabled]) = 0 AND BackupCTE.VersionName like 'Microsoft SQL Server 2000 %' THEN '1'
ELSE CONVERT(varchar,BackupCTE.[SADisabled])
END AS [SADisabled]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.ServiceAccount = 0 THEN '-1'
WHEN StdServiceAccount.IsValid = 1
OR BackupCTE.ServiceAccount IN ('CO\lpsqldbadmin','lpsqldbadmin#CO.IHC.COM')
THEN '1'
ELSE '0' END AS ServiceAccount
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[ServicePackFlag] = 0 THEN '-1' Else BackupCTE.[ServicePack] END AS [ServicePack]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[MaxMemory] = 0 THEN '-1' Else BackupCTE.[MaxMemory] END AS [MaxMemory]
,[JobName]
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[JobOwner] = 0 THEN '-1'
WHEN BackupCTE.JobOwner NOT IN ('SA') AND JobEnabled = 1 AND DELETED IS NULL THEN '0'
ELSE '1' END AS JobOwner
,[JobEnabled]
,CASE WHEN BackupCTE.EnvironmentType = 'PROD' AND BackupCTE.[Primary] NOT IN ('Tamie Jensen', 'Chase Mahony','Megna Musapeta','Aaron Uppencamp') THEN '0'
WHEN BackupCTE.EnvironmentType = 'STBY' AND BackupCTE.[Primary] NOT IN ('Tamie Jensen', 'Chase Mahony','Megna Musapeta','Aaron Uppencamp') THEN '0'
ELSE '1' END AS IsNonPrimary
,CASE WHEN BackupCTE.EnvironmentType = 'PROD' AND BackupCTE.[Secondary] IN ('NONE') THEN '0'
WHEN BackupCTE.EnvironmentType = 'STBY' AND BackupCTE.[Secondary] IN ('NONE') THEN '0'
ELSE '1' END AS IsNonSecondary
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.[MaxMemory] = 0 THEN '-1'
WHEN BackupCTE.[MaxMemory]%8 = 0 THEN '1'
ELSE '0' END AS FlagMemory
,CASE WHEN BackupCTE.JobName NOT LIKE '%Insure%'
THEN
CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.MaintenanceJob = 0 THEN '-1'
WHEN JobSchMultiplier < 0 THEN '1' --One Time Job. No Need To Flag
WHEN DATEDIFF(HH, BackupCTE.JobRunDate, GETDATE()) > 24*JobSchMultiplier THEN '0'
ELSE '1'
END
ELSE '1' END AS MaintenanceJob
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.ServicePackFlag = 0 THEN '-1'
WHEN LTRIM(RTRIM(SUBSTRING(PatchingStds.ServicePack,3, LEN(PatchingStds.ServicePack)-2))) > ISNULL(LTRIM(RTRIM(SUBSTRING(InstanceSQLDTl.ServicePack,3,
LEN(InstanceSQLDTl.ServicePack)-2))),0) THEN '0'
WHEN LTRIM(RTRIM(SUBSTRING(VersionName,CHARINDEX('-',VersionName )+1,abs(CASE WHEN CHARINDEX('(',VersionName ) > 0 THEN CHARINDEX('(',VersionName )-CHARINDEX('-',VersionName) ELSE len(VersionName)-CHARINDEX('-',VersionName) end)))) <> LTRIM(RTRIM(PatchingStds.SQLBuild)) THEN '2'
ELSE '1' END AS ServicePackFlag
,VersionName
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.SAViolations = 0 THEN '-1'
WHEN LoginName Not IN ('CO\DBA Group','CO\DBAdmin') AND SYSAdmin = 1 OR SecurityAdmin = 1 OR ServerAdmin = 1 OR SetupAdmin = 1 OR ProcessAdmin = 1 OR DiskAdmin = 1
OR DBCreator = 1 OR BulkAdmin = 1 THEN '0'
ELSE '1' END AS SAViolations
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.IsBackupShare = 0 THEN '-1'
WHEN NOT (BackupCTE.[BackupShare] LIKE '\\CO.IHC.COM%' OR BackupCTE.[BackupShare] LIKE '\\CO-LP-SQL1%' OR BackupCTE.[BackupShare] LIKE '\\CO-LP-SQL2%'
OR BackupCTE.[BackupShare] LIKE '\\CO-TX-VAULT2%' OR BackupCTE.[BackupShare] LIKE '\\co-tx-vpdsfile2\txPDSsqlBackups%' AND BackupCTE.[BackupShare] NOT LIKE '%Test') OR BackupCTE.[BackupShare] = 'NONE LISTED' THEN '0'
ELSE '1' END AS IsBackupShare
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.Tempdb_DataFileCount = 0 THEN '-1'
WHEN TEMPDBFileCount.Tempdb_DataFileCount >= 8 OR TEMPDBFileCount.Tempdb_DataFileCount > TEMPDBFileCount.OptimalTempdbFilecount THEN '1'
WHEN TEMPDBFileCount.OptimalTempdbFilecount > TEMPDBFileCount.Tempdb_DataFileCount THEN '0'
ELSE '1'END AS Tempdb_DataFileCount
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.DataAutoGrow = 0 THEN '-1' ELSE BackupCTE.DataAutoGrow END AS DataAutoGrow
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.LogAutoGrow = 0 THEN '-1' ELSE BackupCTE.LogAutoGrow END AS LogAutoGrow
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.MaintVersion = 0 THEN '-1' ELSE BackupCTE.MaintVersion END AS MaintVersion
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.MaintVersion = 0 THEN '-1'
WHEN BackupCTE.MaintVersion = 2.02 OR BackupCTE.MaintVersion = 2.03 THEN '1'
ELSE '0' END AS FlagMaintVersion
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.DBCompatibilityLevel = 0 THEN '-1'
WHEN BackupCTE.DBCompatibilityLevel < 90 THEN '0'
ELSE '1' END AS DBCompatibilityLevel
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.FlagVersionName = 0 THEN '-1'
WHEN NOT (BackupCTE.VersionName LIKE 'Microsoft SQL Server 2005%' OR BackupCTE.VersionName LIKE 'Microsoft SQL Server 2000%') THEN '1'
ELSE '0' END AS FlagVersionName
,CASE WHEN DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL AND ComplianceReportExceptions.VLFCount = 0 THEN '-1'
ELSE BackupCTE.VLFCount END AS VLFCount
Into #FinalData
FROM [DBAPP].InstanceSQLDtl
LEFT JOIN #BackupCTE BackupCTE ON InstanceSQLDtl.InstanceID = BackupCTE.InstanceID
LEFT JOIN [DBAPP].[SQLPatchingStandards] PatchingStds ON LTRIM(RTRIM(LEFT(VersionName, CHARINDEX('-', VersionName)-1))) = LTRIM(RTRIM(LEFT
(PatchingStds.SQLVersion,CHARINDEX('-',PatchingStds.SQLVersion)-1)))
LEFT JOIN [DBAPP].[ComplianceReportExceptions] ON ComplianceReportExceptions.InstanceName = BackupCTE.InstanceName
LEFT JOIN [DBAPP].[TEMPDBFileCount] ON InstanceSQLDtl.InstanceID = [TEMPDBFileCount].InstanceID AND Type_DESC = 'ROWS'
LEFT JOIN DBO.fnGetServiceNames() StdServiceAccount ON BackupCTE.InstanceID = StdServiceAccount.InstanceID
Where BackupCTE.[InstanceName] IS NOT NULL
ORDER BY [InstanceName]
That much string manipulation and CASE statements are just always going to be slow. Maybe you can run it as a nightly batch process into a datamart? Otherwise, here are a few tips:
Since many of your CASE statements are testing for ...InstanceName IS NULL, you can split the query in half and use UNION ALL to join together the records where it is and is not null (see example). This will remove a bunch of CASE checks.
Don't use WHERE IN('SA') if there's only one item, use not-equal (<>) instead.
If at all possible, avoid doing string manipulation in a JOIN condition (...PatchingStds ON LTRIM(RTRIM(LEFT(VersionName...). Try to store those fields somewhere, either in a dedicated column or as persisted, computed columns. That way you can put in index on that field to make the join much faster.
Have indexes on the join fields where possible, subject to many factors, but mostly just don't have too many indexes on a single table because that will slow down INSERT statements.
SELECT DISTINCT
BackupCTE.[InstanceName]
, EnvironmentType = CASE WHEN ComplianceReportExceptions.EnvironmentType = 0 THEN '-1' ELSE CONVERT(VARCHAR, BackupCTE.EnvironmentType) END
, [InstanceStatus] = CASE WHEN ComplianceReportExceptions.InstanceStatus = 0 THEN '-1' ELSE CONVERT(VARCHAR,BackupCTE.InstanceStatus) END
, BackupCTE.[BackupShare]
, DatabaseOwner =
CASE WHEN ComplianceReportExceptions.DatabaseOwner = 0 THEN '-1'
WHEN ISNULL(BackupCTE.IsMirroringEnabled,0) = 0
AND BackupCTE.DatabaseOwner <> 'SA'
AND BackupCTE.DatabaseStatus = 'Normal'
AND BackupCTE.DatabaseReadOnly = 0
AND ISNULL(BackupCTE.IsDatabaseSnapshot,0) = 0
THEN '0'
ELSE '1'
END
-- Etc...
INTO #FinalData
FROM [DBAPP].InstanceSQLDtl
LEFT JOIN #BackupCTE BackupCTE ON InstanceSQLDtl.InstanceID = BackupCTE.InstanceID
LEFT JOIN [DBAPP].[SQLPatchingStandards] PatchingStds ON LTRIM(RTRIM(LEFT(VersionName, CHARINDEX('-', VersionName)-1))) = LTRIM(RTRIM(LEFT
(PatchingStds.SQLVersion,CHARINDEX('-',PatchingStds.SQLVersion)-1)))
LEFT JOIN [DBAPP].[ComplianceReportExceptions] ON ComplianceReportExceptions.InstanceName = BackupCTE.InstanceName
LEFT JOIN [DBAPP].[TEMPDBFileCount] ON InstanceSQLDtl.InstanceID = [TEMPDBFileCount].InstanceID AND Type_DESC = 'ROWS'
LEFT JOIN DBO.fnGetServiceNames() StdServiceAccount ON BackupCTE.InstanceID = StdServiceAccount.InstanceID
WHERE BackupCTE.[InstanceName] IS NOT NULL
AND DBAPP.ComplianceReportExceptions.InstanceName IS NOT NULL
--****************
UNION ALL
--****************
SELECT DISTINCT
BackupCTE.[InstanceName]
, EnvironmentType = CONVERT(VARCHAR,BackupCTE.EnvironmentType)
, [InstanceStatus] = CONVERT(VARCHAR,BackupCTE.InstanceStatus)
, BackupCTE.[BackupShare]
, DatabaseOwner =
CASE
WHEN ISNULL(BackupCTE.IsMirroringEnabled,0) = 0
AND BackupCTE.DatabaseOwner <> 'SA'
AND BackupCTE.DatabaseStatus = 'Normal'
AND BackupCTE.DatabaseReadOnly = 0
AND ISNULL(BackupCTE.IsDatabaseSnapshot,0) = 0
THEN '0'
ELSE '1'
END
-- Etc...
INTO #FinalData
FROM [DBAPP].InstanceSQLDtl
LEFT JOIN #BackupCTE BackupCTE ON InstanceSQLDtl.InstanceID = BackupCTE.InstanceID
LEFT JOIN [DBAPP].[SQLPatchingStandards] PatchingStds ON LTRIM(RTRIM(LEFT(VersionName, CHARINDEX('-', VersionName)-1))) = LTRIM(RTRIM(LEFT
(PatchingStds.SQLVersion,CHARINDEX('-',PatchingStds.SQLVersion)-1)))
LEFT JOIN [DBAPP].[ComplianceReportExceptions] ON ComplianceReportExceptions.InstanceName = BackupCTE.InstanceName
LEFT JOIN [DBAPP].[TEMPDBFileCount] ON InstanceSQLDtl.InstanceID = [TEMPDBFileCount].InstanceID AND Type_DESC = 'ROWS'
LEFT JOIN DBO.fnGetServiceNames() StdServiceAccount ON BackupCTE.InstanceID = StdServiceAccount.InstanceID
WHERE BackupCTE.[InstanceName] IS NOT NULL
AND DBAPP.ComplianceReportExceptions.InstanceName IS NULL
--****************
ORDER BY [InstanceName]
Below are the possibilities which causes to degrade the performance of an query,
Do not convert colum value at on clause instead of this create a separate colum and pre-populated the conversion, if you use conversion
it prohibit using indexes to search records in table.
Use with(nolock)
Distinct & order by are costly operations to the query , if you don’t required remove it from query.
I have 2 tables like this:
Table CT: Number, CtID, Date, CTIE
Table VT: Number, VtID, Quantities
And my code:
SELECT
MAX(CT.Date), MAX(CT.CtID), VT.VtID,
SUM(VT.Quantities) AS SumVT,
CASE
WHEN CT.CTIE = 0 THEN SUM(VT.Quantities)
ELSE 0
END AS IMPORT,
CASE
WHEN CT.CTIE = 1 THEN SUM(VT.Quantities)
ELSE 0
END AS EXPORT
FROM
CT
INNER JOIN
VT ON CT.Number = VT.Number
GROUP BY
VT.VtID, CT.CTIE
ORDER BY
VT.VtID
This code works fine but the result is not what I want. With some VtID that have both CTIE = 1 and CTIE = 1, SQL now returns 2 separate rows with same VtID, one for CTIE = 0 and one for CTIE = 1. But I need it to display only 1 row for each VtID instead of 2.
Remove CT.CTIE in the group by and place your case statements inside the aggregate function
SElECT
MAX(CT.Date), MAX(CT.CtID), VT.VtID, SUM(VT.Quantities) AS SumVT,
SUM(CASE WHEN CT.CTIE = 0 THEN VT.Quantities ELSE 0 END) AS IMPORT,
SUM(CASE WHEN CT.CTIE = 1 THEN VT.Quantities ELSE 0 END) AS EXPORT
FROM CT INNER JOIN VT ON CT.Number=VT.Number
GROUP BY VT.VtID
ORDER by VT.VtID
I have something like
(COMPLEX_EXPRESSION_N stands for a long subquery)
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
AllChecksOk = Case WHEN
(FirstCheck + SecondCheck + Third CHeck = 3)
Then 'OK' Else 'No' End
from
AllOperationsTable
Is it possible to use FirstCheck, SecondCheck, ThirdCheck as I did in the AllChecksOk line?
I am not concerned about performance, this is something that is manually run once a day on a very small number of records, I just want to avoid to create views, tables or temporary tables and keep all in a single select statement.
As an altenrative I can do this, but it makes the query less readable (as I need to write twice every complex expression):
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
AllChecksOk = Case WHEN
(COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+
COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
from
AllOperationsTable
You can't reference a column alias in the select but you can use a CTE as below.
;WITH CTE AS
(
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end
from
AllOperationsTable
)
SELECT *,
AllChecksOk = Case WHEN
(COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+
COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
FROM CTE
You can also use CROSS APPLY to define the 3 column aliases then reference them in the main SELECT list as in this example.
Below is a derived table solution
SELECT
T.ID_Operation,
FirstCheck = CASE WHEN T.Expr1 = 0 THEN 0 ELSE 1 END,
SecondCheck = CASE WHEN T.Expr2 = 0 THEN 0 ELSE 1 END,
ThirdCheck = CASE WHEN T.Expr3 = 0 THEN 0 ELSE 1 END,
AllChecksOk = CASE WHEN T.Expr1 + T.Expr2 + T.Expr3 = 3 THEN 'OK' ELSE 'No' END
FROM
(
SELECT
ID_Operation,
Expr1 = (COMPLEX_EXPRESSION_1),
Expr2 = (COMPLEX_EXPRESSION_2),
Expr3 = (COMPLEX_EXPRESSION_3)
FROM
AllOperationsTable
) T
Personally, I find using CTE or derived tables a bit confusing for this purpose, as you have to nest things one level and think about the nesting impliciations. A much simpler approach (at least in my opinion) is to use APPLY (or standard SQL LATERAL in other RDBMS) to generate column expression aliases:
SELECT
ID_Operation,
FirstCheck,
SecondCheck,
ThirdCheck,
AllChecksOk = CASE
WHEN FirstCheck + SecondCheck + ThirdCheck = 3 THEN 'OK' ELSE 'NO'
END
FROM
AllOperationsTable
CROSS APPLY (
SELECT
FirstCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END,
SecondCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END,
ThirdCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END
) t