Get the Count based on Conditions - sql-server

I am using SQL Server 2008 R2. I have one table say BrokerTable
-----------------------------------
BrokerCode | Rank | BrokerId
-----------------------------------
1527339 | 1 | 3880
1527488 | 1 | 7550
1527366 | 1 | 3854
1527400 | 1 | 1519
1527358 | 1 | 3862
1527357 | 1 | 3863
Below is my part of query which calculate Business of Broker which are in above table. For example BrokerId 3880
SELECT CONVERT(DECIMAL(18, 2), SUM(T.Amount11))
FROM ( SELECT ISNULL(( CASE WHEN mb.PlanType = 'MULTIPLE'
THEN CASE WHEN mb.Mode = 'MLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'MLY'
AND bcm.MLY_From <= mb.InstallmentNo AND bcm.MLY_To >= mb.InstallmentNo
) ) / 100 ) WHEN mb.Mode = 'QLY' THEN ( ( ( SUM(SelfAmount)
+ SUM(UnitAmount) ) * ( SELECT bcm.PromoteeQuota FROM
dbo.BusinessCalcMaster AS bcm WHERE bcm.PlanType = mb.PlanType
AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year
AND mb.Mode = 'QLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 )
WHEN mb.Mode = 'HLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm WHERE
bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'HLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 )
WHEN mb.Mode = 'YLY' THEN ( ( ( SUM(SelfAmount) + SUM(UnitAmount) )
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName
AND bcm.Year = mb.Year AND mb.Mode = 'YLY' AND bcm.MLY_From <= mb.InstallmentNo
AND bcm.MLY_To >= mb.InstallmentNo ) ) / 100 ) END
WHEN mb.PlanType = 'SINGLE' THEN ( ( SUM(SelfAmount) + SUM(UnitAmount)
* ( SELECT bcm.PromoteeQuota FROM dbo.BusinessCalcMaster
AS bcm WHERE bcm.PlanType = mb.PlanType
AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year ) ) / 100 )
END ), 0) AS Amount11 , mb.InstallmentNo
FROM dbo.MemberBusiness AS mb WHERE mb.BrokerId = 3880
AND ( ( mb.PlanType = 'MULTIPLE' AND ( ( mb.Mode = 'HLY'
AND mb.InstallmentNo = 2 ) OR ( mb.Mode = 'QLY' AND mb.InstallmentNo >= 2
AND mb.InstallmentNo <= 4 ) OR ( mb.Mode = 'MLY' AND mb.InstallmentNo >= 2
AND mb.InstallmentNo <= 12 ) OR ( mb.InstallmentNo = 1 ) ))
OR ( mb.PlanType = 'SINGLE' ) )AND mb.Date >= '2013-02-01 00:00:00.000'
AND mb.Date <= '2013-02-28 00:00:00.000' GROUP BY mb.Mode , mb.Year ,
mb.PlanName , mb.PlanType , mb.InstallmentNo ) AS T
In BrokerTable there may be any number of Brokers. I want to calculate Business of each broker from BrokerTable and get number of Brokers whose Business is greater than 15000.
I can use a cursor but as I told there may be any number of Brokers in table, query takes more time to execute. How can I get result in less time or easiest way?. Thanks

Try:
SELECT B.BrokerId,
MAX(B.BrokerCode) BrokerCode,
CONVERT(DECIMAL(18, 2), SUM(T.Amount11)) BrokerAMount
FROM BrokerTable B
JOIN (SELECT CASE WHEN mb.PlanType = 'MULTIPLE' AND mb.Mode in ('MLY', 'QLY', 'HLY', 'YLY')
THEN ( SUM(SelfAmount) + SUM(UnitAmount) ) *
( SELECT bcm.PromoteeQuota
FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year
AND bcm.MLY_From <= mb.InstallmentNo AND bcm.MLY_To >= mb.InstallmentNo)
/ 100
WHEN mb.PlanType = 'SINGLE'
THEN ( SUM(SelfAmount) + SUM(UnitAmount) *
( SELECT bcm.PromoteeQuota
FROM dbo.BusinessCalcMaster AS bcm
WHERE bcm.PlanType = mb.PlanType AND bcm.PlanName = mb.PlanName AND bcm.Year = mb.Year )
) / 100
END AS Amount11,
mb.BrokerId,
mb.InstallmentNo
FROM dbo.MemberBusiness AS mb
WHERE ( ( mb.PlanType = 'MULTIPLE' AND
( ( mb.Mode = 'HLY' AND mb.InstallmentNo = 2 ) OR
( mb.Mode = 'QLY' AND mb.InstallmentNo >= 2 AND mb.InstallmentNo <= 4 ) OR
( mb.Mode = 'MLY' AND mb.InstallmentNo >= 2 AND mb.InstallmentNo <= 12 ) OR
mb.InstallmentNo = 1
)
) OR
mb.PlanType = 'SINGLE'
) AND
mb.Date >= '2013-02-01 00:00:00.000' AND mb.Date <= '2013-02-28 00:00:00.000'
GROUP BY mb.BrokerId , mb.Mode , mb.Year , mb.PlanName , mb.PlanType , mb.InstallmentNo
) AS T
ON B.BrokerId = T.BrokerId
GROUP BY B.BrokerId
HAVING SUM(T.Amount11) > 15000

Related

convert SQL server query to snowflake , i need help in calling local variable using javascript

# sql server query:#
CREATE FUNCTION [dbo].[fnCurrencyExchange]
(#ExchngType NVARCHAR(30),
#InCurrMode NVARCHAR(10),
#OutCurMode NVARCHAR(10),
#InDate DATE)
RETURNS DECIMAL(17, 6)
BEGIN
DECLARE #lExchangeRate DECIMAL(17, 7);
DECLARE #2ExchangeRate DECIMAL(17, 7);
DECLARE #3ExchangeRate DECIMAL(17, 7);
DECLARE #4ExchangeRate DECIMAL(17, 7);
DECLARE #currdate NVARCHAR(30);
IF ISNULL(#ExchngType,'') = '' -- Default use Balance Sheet Exchnage rate
SET #ExchngType = 'Income Statement';
IF ( #InCurrMode = #OutCurMode AND #InCurrMode IS NOT NULL AND #OutCurMode IS NOT NULL )
RETURN 1;
IF #InDate = ''
SET #currdate = getDate();
Else
SET #currdate = #InDate;
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NOT NULL
RETURN #lExchangeRate;
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
END
IF #lExchangeRate IS NOT NULL
RETURN ( 1 / #lExchangeRate );
IF #lExchangeRate IS NULL
BEGIN
SELECT TOP 1 #lExchangeRate = ExchangeRate
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #InCurrMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #lExchangeRate IS NULL
SELECT TOP 1 #lExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate
, Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #InCurrMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT TOP 1 #2ExchangeRate = exchangerate
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = #OutCurMode
AND a.ToCurrency = 'USD'
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
IF #2ExchangeRate IS NULL
SELECT TOP 1 #2ExchangeRate = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a.ExchangeRate ExchangeRate,
Row_number() OVER (ORDER BY a.ValidFrom DESC) Id
FROM [STG].[stgFXRateOut] a
WHERE a.FromCurrency = 'USD'
AND a.ToCurrency = #OutCurMode
AND a.ValidFrom <= #currdate
AND a.ExchangeRatetype = #ExchngType
) f
WHERE id = 1;
SELECT #3ExchangeRate = ( #lExchangeRate / #2ExchangeRate );
END
RETURN Isnull(#3ExchangeRate, 0);
END
convert this into snowflake , need help on this on?
i tried but i was unsuccessful
CREATE OR REPLACE FUNCTION "fn_FncurrencyExchange"("ExchngType" NVARCHAR(30),"InCurrMode" NVARCHAR(10),"OutCurMode" NVARCHAR(10),"InDate" DATE)
RETURNS NUMBER(17,6)
LANGUAGE JAVASCRIPT
COMMENT='Create Date: 2022-11-25 Author: Performalytic Team '
AS '
var lExchangeRate =p1;
var 2ExchangeRate =p2;
var 3ExchangeRate =p3;
var 4ExchangeRate =p4;
var currdate =p5;
IF (ISNULL(ExchngType,'') = '' )
{ ExchngType = ''Income Statement'';
}
IF ( InCurrMode = OutCurMode AND InCurrMode IS NOT NULL AND OutCurMode IS NOT NULL )
RETURN 1;
IF InDate = ''
{ p5 = CURRENT_DATE();
}
Else
{ p5 = InDate;
}
SELECT p1 = ExchangeRate
FROM (
SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NOT NULL
RETURN p1;
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p1 IS NOT NULL
RETURN ( 1 / p1 );
IF p1 IS NULL
BEGIN
SELECT p1 = ExchangeRate
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = InCurrMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
IF p1 IS NULL
SELECT p1 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate
, Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = InCurrMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p2 = exchangerate
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = OutCurMode
AND a."ToCurrency" = ''USD''
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
END
IF p2 IS NULL
BEGIN
SELECT p2 = 1 / (CASE WHEN exchangerate = 0 THEN 1 ELSE exchangerate END)
FROM (SELECT a."ExchangeRate" ExchangeRate,
Row_number() OVER (ORDER BY a."ValidFrom" DESC) Id
FROM DBO."DimFXRateOut" a
WHERE a."FromCurrency" = ''USD''
AND a."ToCurrency" = OutCurMode
AND a."ValidFrom" <= p5
AND a."ExchangeRatetype" = ExchngType
) f
WHERE id = 1 LIMIT 1;
SELECT p3 = ( p1 / p2 );
END
RETURN ISNULL(p3, 0);
END
;`;
You set the language to JavaScript, you started with JS commands but you try to run SQLs directly. It is also defined as UDF, in this case you can't call SQLs from JavaScript.
Do you need to create a UDF? Then check this one: https://docs.snowflake.com/en/developer-guide/udf/sql/udf-sql.html
If you want conditionals etc, and run SQL directly, consider SQL scripting (but it will be a stored procedure): https://docs.snowflake.com/en/developer-guide/snowflake-scripting/index.html
You may also want to check writing Stored Procedures in JavaScript: https://docs.snowflake.com/en/sql-reference/stored-procedures-javascript.html

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

OR in INNER JOIN ON clause

I have some problem with ERP system.
I found problem is query with INNER JOIN.
Query (JOIN) look like this:
INNER JOIN nz__finanse fin2 ON (
fin1.nzf_id <> fin2.nzf_id
AND
(
spfin.nzs_iddlugu = fin2.nzf_id
OR
spfin.nzs_idsplaty = fin2.nzf_id
)
)
OR
(
fin1.nzf_id = fin2.nzf_id
AND
spfin.nzs_iddlugu = fin2.nzf_id
AND
spfin.nzs_idsplaty IS NULL
)
If I delete one of condition, query works fine, but with both conditions (and OR) I have to wait several minutes to result.
I can't modify query so I have question:
is it possible to some optymalisation this query (for this OR in conditions)?
Thanks.
Regards.
full query (result in serval minutes):
SELECT POZ1.dko_konto AS dko_Konto,
FIN1.nzf_typobiektu AS nzf_TypObiektu,
FIN1.nzf_idobiektu AS nzf_IdObiektu,
FIN1.nzf_numerpelny AS nzf_NumerPelny,
Roznica = CASE WHEN FIN1.nzf_typ IN (39, 42, 18, 20) THEN (Round( CASE
WHEN
FIN1.nzf_typ
IN (39, 40) THEN FIN1.nzf_wartoscpierwotna ELSE
FIN1.nzf_wartosc END,
2 ) - dbo.Fninsmuldiv( dbo.Fnwartoscrozrachunkownadzien(
FIN1.nzf_id,
'20171231', CASE WHEN FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END
),
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek, 2 ) - Sum( dbo.Fnfin_wartoscwpln(
FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek, CASE WHEN FIN2.nzf_id =
SPFIN.nzs_idsplaty
THEN
SPFIN.nzs_wartoscwaluta ELSE SPFIN.nzs_wartoscwalutadlugu END )
) )
ELSE -(Round( CASE
WHEN FIN1.nzf_typ IN (39, 40) THEN FIN1.nzf_wartoscpierwotna
ELSE
FIN1.nzf_wartosc END, 2 ) - dbo.Fninsmuldiv(
dbo.Fnwartoscrozrachunkownadzien(
FIN1.nzf_id, '20171231', CASE WHEN FIN1.nzf_typ IN (39, 40)
THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END
),
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek, 2 ) - Sum( dbo.Fnfin_wartoscwpln(
FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek, CASE WHEN FIN2.nzf_id =
SPFIN.nzs_idsplaty
THEN
SPFIN.nzs_wartoscwaluta ELSE SPFIN.nzs_wartoscwalutadlugu END )
) )END
+ Sum( Isnull(
CASE WHEN FIN3.nzf_typ = 45 THEN FIN3.nzf_wartosc WHEN
FIN3.nzf_typ =
46 THEN -FIN3.nzf_wartosc ELSE 0 END, 0 ) )
FROM nz__finanse FIN1
INNER JOIN nz_finansesplata SPFIN
ON SPFIN.nzs_iddlugu = FIN1.nzf_id
OR SPFIN.nzs_idsplaty = FIN1.nzf_id
INNER JOIN nz__finanse FIN2
ON ( FIN1.nzf_id <> FIN2.nzf_id
AND ( SPFIN.nzs_iddlugu = FIN2.nzf_id
OR SPFIN.nzs_idsplaty = FIN2.nzf_id ) )
OR ( FIN1.nzf_id = FIN2.nzf_id
AND SPFIN.nzs_iddlugu = FIN2.nzf_id
AND SPFIN.nzs_idsplaty IS NULL )
LEFT JOIN nz__finanse FIN3
ON FIN3.nzf_idrozliczenia = SPFIN.nzs_id
INNER JOIN nz_rozdekret RD1
ON FIN1.nzf_id = RD1.nzd_idrozrachunku
INNER JOIN dkr_pozycja POZ1
ON POZ1.dko_id = RD1.nzd_iddekretu
AND POZ1.dko_datadekretacji <= '20171231'
INNER JOIN pk_plankont PK1
ON POZ1.dko_konto = PK1.ko_nr
AND POZ1.dko_idroku = PK1.ko_idrokuobrotowego
LEFT JOIN dkr__dokument DOK1
ON DOK1.dkr_id = POZ1.dko_iddokumentu
LEFT JOIN adr__ewid ADR1
ON ADR1.adr_id = FIN1.nzf_idadresu
WHERE RD1.nzd_idroku = 3
AND PK1.ko_id IN ( 14966 )
AND FIN1.nzf_data <= '20171231'
AND SPFIN.nzs_data <= '20171231'
AND FIN1.nzf_typ IN ( 17, 18, 19, 20,
39, 40, 41, 42,
45, 46 )
GROUP BY FIN1.nzf_id,
FIN1.nzf_typobiektu,
FIN1.nzf_idobiektu,
FIN1.nzf_iddokumentauto,
FIN1.nzf_typ,
FIN1.nzf_korekta,
FIN1.nzf_data,
FIN1.nzf_numerpelny,
FIN1.nzf_tytulem,
ADR1.adr_symbol,
ADR1.adr_nazwa,
FIN1.nzf_transakcja,
FIN1.nzf_terminplatnosci,
FIN1.nzf_wartoscpierwotna,
FIN1.nzf_wartoscpierwotnawaluta,
FIN1.nzf_wartosc,
FIN1.nzf_wartoscwaluta,
FIN1.nzf_splata,
FIN1.nzf_splatawaluta,
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek,
FIN1.nzf_idwaluty,
POZ1.dko_konto,
POZ1.dko_kwotawn,
POZ1.dko_kwotama,
DOK1.dkr_nrpelny,
FIN1.nzf_zrodlo,
RD1.nzd_status
HAVING Sum(CASE
WHEN FIN3.nzf_id IS NULL THEN 1
ELSE 0
END) = 0
AND CASE WHEN FIN1.nzf_typ IN (39, 42, 18, 20) THEN (Round( CASE WHEN
FIN1.nzf_typ
IN (39, 40) THEN FIN1.nzf_wartoscpierwotna ELSE FIN1.nzf_wartosc END,
2 ) -
dbo.Fninsmuldiv( dbo.Fnwartoscrozrachunkownadzien( FIN1.nzf_id,
'20171231',
CASE WHEN
FIN1.nzf_typ IN (39, 40) THEN FIN1.nzf_wartoscpierwotnawaluta ELSE
FIN1.nzf_wartoscwaluta
END ), FIN1.nzf_kurs, FIN1.nzf_liczbajednostek, 2 ) - Sum(
dbo.Fnfin_wartoscwpln( FIN2.nzf_kurs, FIN2.nzf_liczbajednostek, CASE
WHEN
FIN2.nzf_id =
SPFIN.nzs_idsplaty THEN SPFIN.nzs_wartoscwaluta ELSE
SPFIN.nzs_wartoscwalutadlugu END ) ) )
ELSE -(Round( CASE WHEN FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotna
ELSE FIN1.nzf_wartosc END, 2 ) - dbo.Fninsmuldiv(
dbo.Fnwartoscrozrachunkownadzien( FIN1.nzf_id, '20171231', CASE WHEN
FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END ),
FIN1.nzf_kurs, FIN1.nzf_liczbajednostek,
2 ) - Sum( dbo.Fnfin_wartoscwpln( FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek,
CASE
WHEN FIN2.nzf_id = SPFIN.nzs_idsplaty THEN SPFIN.nzs_wartoscwaluta
ELSE
SPFIN.nzs_wartoscwalutadlugu END ) ) )END + Sum( Isnull( CASE WHEN
FIN3.nzf_typ = 45 THEN
FIN3.nzf_wartosc WHEN FIN3.nzf_typ = 46 THEN -FIN3.nzf_wartosc ELSE 0
END, 0
) ) <> 0
modified query (delete one of part alternative in INNER JOIN - result in servat seconds):
SELECT POZ1.dko_konto AS dko_Konto,
FIN1.nzf_typobiektu AS nzf_TypObiektu,
FIN1.nzf_idobiektu AS nzf_IdObiektu,
FIN1.nzf_numerpelny AS nzf_NumerPelny,
Roznica = CASE WHEN FIN1.nzf_typ IN (39, 42, 18, 20) THEN (Round( CASE
WHEN
FIN1.nzf_typ
IN (39, 40) THEN FIN1.nzf_wartoscpierwotna ELSE
FIN1.nzf_wartosc END,
2 ) - dbo.Fninsmuldiv( dbo.Fnwartoscrozrachunkownadzien(
FIN1.nzf_id,
'20171231', CASE WHEN FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END
),
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek, 2 ) - Sum( dbo.Fnfin_wartoscwpln(
FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek, CASE WHEN FIN2.nzf_id =
SPFIN.nzs_idsplaty
THEN
SPFIN.nzs_wartoscwaluta ELSE SPFIN.nzs_wartoscwalutadlugu END )
) )
ELSE -(Round( CASE
WHEN FIN1.nzf_typ IN (39, 40) THEN FIN1.nzf_wartoscpierwotna
ELSE
FIN1.nzf_wartosc END, 2 ) - dbo.Fninsmuldiv(
dbo.Fnwartoscrozrachunkownadzien(
FIN1.nzf_id, '20171231', CASE WHEN FIN1.nzf_typ IN (39, 40)
THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END
),
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek, 2 ) - Sum( dbo.Fnfin_wartoscwpln(
FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek, CASE WHEN FIN2.nzf_id =
SPFIN.nzs_idsplaty
THEN
SPFIN.nzs_wartoscwaluta ELSE SPFIN.nzs_wartoscwalutadlugu END )
) )END
+ Sum( Isnull(
CASE WHEN FIN3.nzf_typ = 45 THEN FIN3.nzf_wartosc WHEN
FIN3.nzf_typ =
46 THEN -FIN3.nzf_wartosc ELSE 0 END, 0 ) )
FROM nz__finanse FIN1
INNER JOIN nz_finansesplata SPFIN
ON SPFIN.nzs_iddlugu = FIN1.nzf_id
OR SPFIN.nzs_idsplaty = FIN1.nzf_id
INNER JOIN nz__finanse FIN2
ON ( FIN1.nzf_id <> FIN2.nzf_id
AND ( SPFIN.nzs_iddlugu = FIN2.nzf_id
OR SPFIN.nzs_idsplaty = FIN2.nzf_id ) )
LEFT JOIN nz__finanse FIN3
ON FIN3.nzf_idrozliczenia = SPFIN.nzs_id
INNER JOIN nz_rozdekret RD1
ON FIN1.nzf_id = RD1.nzd_idrozrachunku
INNER JOIN dkr_pozycja POZ1
ON POZ1.dko_id = RD1.nzd_iddekretu
AND POZ1.dko_datadekretacji <= '20171231'
INNER JOIN pk_plankont PK1
ON POZ1.dko_konto = PK1.ko_nr
AND POZ1.dko_idroku = PK1.ko_idrokuobrotowego
LEFT JOIN dkr__dokument DOK1
ON DOK1.dkr_id = POZ1.dko_iddokumentu
LEFT JOIN adr__ewid ADR1
ON ADR1.adr_id = FIN1.nzf_idadresu
WHERE RD1.nzd_idroku = 3
AND PK1.ko_id IN ( 14966 )
AND FIN1.nzf_data <= '20171231'
AND SPFIN.nzs_data <= '20171231'
AND FIN1.nzf_typ IN ( 17, 18, 19, 20,
39, 40, 41, 42,
45, 46 )
GROUP BY FIN1.nzf_id,
FIN1.nzf_typobiektu,
FIN1.nzf_idobiektu,
FIN1.nzf_iddokumentauto,
FIN1.nzf_typ,
FIN1.nzf_korekta,
FIN1.nzf_data,
FIN1.nzf_numerpelny,
FIN1.nzf_tytulem,
ADR1.adr_symbol,
ADR1.adr_nazwa,
FIN1.nzf_transakcja,
FIN1.nzf_terminplatnosci,
FIN1.nzf_wartoscpierwotna,
FIN1.nzf_wartoscpierwotnawaluta,
FIN1.nzf_wartosc,
FIN1.nzf_wartoscwaluta,
FIN1.nzf_splata,
FIN1.nzf_splatawaluta,
FIN1.nzf_kurs,
FIN1.nzf_liczbajednostek,
FIN1.nzf_idwaluty,
POZ1.dko_konto,
POZ1.dko_kwotawn,
POZ1.dko_kwotama,
DOK1.dkr_nrpelny,
FIN1.nzf_zrodlo,
RD1.nzd_status
HAVING Sum(CASE
WHEN FIN3.nzf_id IS NULL THEN 1
ELSE 0
END) = 0
AND CASE WHEN FIN1.nzf_typ IN (39, 42, 18, 20) THEN (Round( CASE WHEN
FIN1.nzf_typ
IN (39, 40) THEN FIN1.nzf_wartoscpierwotna ELSE FIN1.nzf_wartosc END,
2 ) -
dbo.Fninsmuldiv( dbo.Fnwartoscrozrachunkownadzien( FIN1.nzf_id,
'20171231',
CASE WHEN
FIN1.nzf_typ IN (39, 40) THEN FIN1.nzf_wartoscpierwotnawaluta ELSE
FIN1.nzf_wartoscwaluta
END ), FIN1.nzf_kurs, FIN1.nzf_liczbajednostek, 2 ) - Sum(
dbo.Fnfin_wartoscwpln( FIN2.nzf_kurs, FIN2.nzf_liczbajednostek, CASE
WHEN
FIN2.nzf_id =
SPFIN.nzs_idsplaty THEN SPFIN.nzs_wartoscwaluta ELSE
SPFIN.nzs_wartoscwalutadlugu END ) ) )
ELSE -(Round( CASE WHEN FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotna
ELSE FIN1.nzf_wartosc END, 2 ) - dbo.Fninsmuldiv(
dbo.Fnwartoscrozrachunkownadzien( FIN1.nzf_id, '20171231', CASE WHEN
FIN1.nzf_typ IN (39, 40) THEN
FIN1.nzf_wartoscpierwotnawaluta ELSE FIN1.nzf_wartoscwaluta END ),
FIN1.nzf_kurs, FIN1.nzf_liczbajednostek,
2 ) - Sum( dbo.Fnfin_wartoscwpln( FIN2.nzf_kurs,
FIN2.nzf_liczbajednostek,
CASE
WHEN FIN2.nzf_id = SPFIN.nzs_idsplaty THEN SPFIN.nzs_wartoscwaluta
ELSE
SPFIN.nzs_wartoscwalutadlugu END ) ) )END + Sum( Isnull( CASE WHEN
FIN3.nzf_typ = 45 THEN
FIN3.nzf_wartosc WHEN FIN3.nzf_typ = 46 THEN -FIN3.nzf_wartosc ELSE 0
END, 0
) ) <> 0
in brief:
change:
INNER JOIN nz__finanse fin2 ON (
fin1.nzf_id <> fin2.nzf_id
AND
(
spfin.nzs_iddlugu = fin2.nzf_id
OR
spfin.nzs_idsplaty = fin2.nzf_id
)
)
OR
(
fin1.nzf_id = fin2.nzf_id
AND
spfin.nzs_iddlugu = fin2.nzf_id
AND
spfin.nzs_idsplaty IS NULL
)
to:
INNER JOIN nz__finanse fin2 ON (
fin1.nzf_id <> fin2.nzf_id
AND
(
spfin.nzs_iddlugu = fin2.nzf_id
OR
spfin.nzs_idsplaty = fin2.nzf_id
)
)
or to:
INNER JOIN nz__finanse fin2 ON
(
fin1.nzf_id = fin2.nzf_id
AND
spfin.nzs_iddlugu = fin2.nzf_id
AND
spfin.nzs_idsplaty IS NULL
)
solving a problem.
Hence the question how to optimize this join (without is editing).

Is there a way to prevent SQL Server from automatically formatting my view query?

It's ok to have a common format, I have mine, me and my team uses the same format when writing SQL.
Now here is the problem: we use SQL Server. I wrote a long view, then, to remember what I did, I opened the "design" of that view. And I noticed that SQL Server completely screwed my format, and applied its own. Even worse, it duplicate simple conditions and make them longer for no reason (maybe I'm judging a bit to fast... but...)
Here is my example, sorry it's a very long condition, you don't have to read it, just notice the format:
WHERE (STATUT_CAND IN (2, 3))
AND
(DATE_DISPO < GETDATE() OR DATE_DISPO IS NULL)
AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0)
AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0)
AND
(NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0'))))
AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577)))
AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE())))
AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR)))))
AND ( EXISTS
(SELECT MATR
FROM Paie.dbo.PAI_HCHQ_PMNT AS dosem
WHERE (MATR = PC.MATR) AND (DATE_FIN > DATEADD (year , -3 , GETDATE() ))) or (select DATE_DERN_PAIE from paie.dbo.PAI_DOS where MATR = PC.MATR) > DATEADD (year , -3 , GETDATE() ) or (select DATE_DERN_PAIE from paie.dbo.PAI_DOS where MATR = PC.MATR) is null)
This way, I know where the MAIN AND are, now when I put this into the view, this is how SQL Server format it :
WHERE (STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND EXISTS
(SELECT MATR
FROM Paie.dbo.PAI_HCHQ_PMNT AS dosem
WHERE (MATR = PC.MATR) AND (DATE_FIN > DATEADD(year, - 3, GETDATE()))) OR
(STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND
((SELECT DATE_DERN_PAIE
FROM Paie.dbo.PAI_DOS
WHERE (MATR = PC.MATR)) > DATEADD(year, - 3, GETDATE())) OR
(STATUT_CAND IN (2, 3)) AND (DATE_DISPO < GETDATE() OR
DATE_DISPO IS NULL) AND
((SELECT COUNT(ID_CAND) AS Expr1
FROM Paie.dbo.PAI_CAND_RESULT_ENTREVUE AS pcre
WHERE (ID_CAND = PC.ID_CAND)) > 0) AND
((SELECT COUNT(MATR) AS Expr1
FROM Paie.dbo.PAI_DOS_EMPL AS PAI_DOS_EMPL_1
WHERE (MATR = PC.MATR) AND (ETAT = 'C14' OR
ETAT = 'C15' OR
ETAT = 'E1') OR
(MATR = PC.MATR) AND (ETAT LIKE 'A%' OR
ETAT LIKE 'P%' OR
ETAT LIKE 'S%') AND (STAT_ENG = 'E1' OR
STAT_ENG = 'P1' OR
STAT_ENG = 'G1')) <= 0) AND (NOT EXISTS
(SELECT ID_CAND
FROM Paie.dbo.PAI_CAND_EMPL AS PAI_CAND_EMPL_1
WHERE (ID_CAND = PC.ID_CAND) AND (MOTIF_EXCLUS IS NOT NULL) AND (MOTIF_EXCLUS NOT IN ('0')))) AND (NOT EXISTS
(SELECT MOT_ABS
FROM Paie.dbo.PAI_DOS_PMNT_ABS AS PAI_DOS_PMNT_ABS_1
WHERE (MATR = PC.MATR) AND (MOT_ABS = '15' OR
MOT_ABS = '16' OR
MOT_ABS = '40' OR
MOT_ABS = '41' OR
MOT_ABS = '45' OR
MOT_ABS = '46' OR
MOT_ABS >= '52' AND MOT_ABS <= '57') OR
(MATR = PC.MATR) AND (MOT_ABS = '01') AND (CODE_PMNT >= 103522 AND CODE_PMNT <= 103541 OR
CODE_PMNT = 103572 OR
CODE_PMNT = 103573 OR
CODE_PMNT = 103577))) AND (NOT EXISTS
(SELECT STAT_ENG
FROM Paie.dbo.PAI_DOS_EMPL AS pados
WHERE (MATR = PC.MATR) AND (DATE_EFF > GETDATE()))) AND (NOT EXISTS
(SELECT MOTIF_AFF
FROM Paie.dbo.GRH_POSTE_AFFECT AS pados
WHERE (PC.MATR = MATR) AND (MOTIF_AFF LIKE '%S%') AND (DATE_EFF =
(SELECT MAX(DATE_EFF) AS Expr1
FROM Paie.dbo.GRH_POSTE_AFFECT AS aff
WHERE (MATR = PC.MATR))))) AND
((SELECT DATE_DERN_PAIE
FROM Paie.dbo.PAI_DOS AS PAI_DOS_1
Not only is it almost impossible to understand anything (personally I don't) BUT IT IS 3 TIMES LONGER THEN THE ONE I WROTE... Unacceptable, is there a way to turn auto format off? If not I'm going to keep my format in a separate file and copy paste it every time.
Don't use the designer. It does horrible things to formatting. Just right click and "script as create to new window". It will maintain your formatting. And as Aaron Bertrand commented you should avoid using any of the visual designers.

how to use coalesce with in, in the where part

How to use Coalesce Command in the following code
PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
in this code
SELECT DISTINCT
[dbo].[test2](A.PIECE_DETAIL ) TOTAL_QUANTITY,
PIECE_LATIN = (SELECT PIECE_LATIN FROM PIECES WHERE PIECE_ID =
(SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_LATIN = (SELECT BRAND_LATIN FROM BRANDS WHERE BRAND_ID =
(SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL )),
BRAND_ID = (SELECT BRAND_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_ID = (SELECT PIECE_ID FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
MODEL_NAME = (SELECT MODEL_NAME FROM PIECES_DETAILS WHERE MODEL_ID = A.PIECE_DETAIL ),
PIECE_DETAIL MODEL_ID,
A.PIECE_STATUS ,
PIECE_STATUS_Name = (SELECT STATUS_Name FROM PIECE_STATUS WHERE STATUS_ID = A.PIECE_STATUS) ,
A.PIECE_DETAIL
FROM DOCUMENT_ITEMS A
WHERE
PIECE_STATUS = 1 and
DOC_SEQ IN (SELECT DOC_SEQ FROM DOCUMENT_HEADER WHERE DOC_TYPE IN (1,3))
AND PIECE_DETAIL in coalesce( PIECE_DETAIL, (SELECT B.MODEL_ID FROM PIECES_DETAILS B WHERE PIECE_ID = #PIECE_ID AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID))
AND [DBO].[GET_WAREHOUSE_QUANTITIES_SPECIAL_ID_EXIST](A.PIECE_DETAIL ,A.SPECIAL_ID )> 0
GROUP BY PIECE_DETAIL ,SPECIAL_ID ,PIECE_STATUS
thanks all
Something like this then:
WHERE PIECE_DETAIL IN
(
SELECT
coalesce(PIECE_DETAIL,B.MODEL_ID)
FROM
PIECES_DETAILS B
WHERE
PIECE_ID = #PIECE_ID
AND B.BRAND_ID=COALESCE(B.BRAND_ID,#BRAND_ID)
)
Edit
Maybe something like this:
WHERE
(
(
FROM_DATE IS NULL AND TO_DATE IS NULL
)
OR
(
BUY_DOC_DATE BETWEEN FROM_DATE AND TO_DATE
)
)

Resources