So I have this SQL Server query:
declare #symbol varchar(8) = '180460';
declare #sdate DATE = '20170630';
declare #edate DATE = '20170704';
IF #symbol = 'TSE00081'
BEGIN
SELECT * from dbo.IndexNames
END
ELSE
BEGIN
SELECT t1.qcode, t4.Name,t1.effectivedate, t1.publishdate, EventMap.Description, t1.SharesChanged, t1.FFW, t1.OldFFW,
IIF(t1.EventCode='SK',t6.IndexName,''), IIF(t1.EventCode='SK',t7.Indexname,''), IIF(t1.Market<>'',t5.IndexName,''), IIF(t3.NameEn<>'',t3.NameEn,t2.NameEn),
IIF(t1.OldSector<>'',t8.NameEn,''), IIF(t1.Allotment1<>0 AND t1.EventCode<>'05', t1.Allotment2/t1.Allotment1,''), t1.SharesUnit
FROM ( dbo.AdvNoticeData as t1 , dbo.IdTable as t4 )
LEFT JOIN dbo.EventMap on t1.EventCode = dbo.EventMap.EventCode
LEFT JOIN dbo.Industries as t2 on t1.SectorAsOf = t2.IndNum
LEFT JOIN dbo.Industries as t3 on t1.Sector = t3.IndNum
LEFT JOIN dbo.Industries as t8 on t1.OldSector = t8.IndNum
LEFT JOIN dbo.IndexNames as t5 on t1.OldMarket = t5.Market
LEFT JOIN dbo.IndexNames as t6 on t1.Scale = t6.Scale
LEFT JOIN dbo.IndexNames as t7 on t1.OldScale = t7.Scale
WHERE (t1.Market=1 or t1.MarketAsOf=1 or (t1.OldMarket=1 and t1.MarketAsOf=''))
and t1.EffectiveDate >= #sdate and t1.EffectiveDate <= #edate and t1.Qcode = t4.Qcode
ORDER BY t1.EffectiveDate, t1.EventCode, t1.Qcode
END
the problem is after the FROM clause. I keep on getting incorrect syntax at ','
When I tried this command (with few modifications) on sqlyog, it works with that comma after the FROM clause. what seems to be the problem? here's the mysql counter part that works:
SELECT t1.qcode, t4.Name,t1.effectivedate, t1.publishdate,
EventMap.Description, t1.SharesChanged, t1.FFW, t1.OldFFW,
IF(t1.EventCode="SK",t6.IndexName,""),
IF(t1.EventCode="SK",t7.Indexname,""),
IF(t1.market<>"",t5.IndexName,""),
IF(t3.NameEn<>"",t3.NameEn,t2.NameEn),
IF(t1.oldSector<>"",t8.NameEn,""),
IF(t1.allotment1<>0 AND t1.eventcode<>"05",t1.allotment2/t1.allotment1,""),
t1.sharesunit
FROM (AdvNoticeData AS t1, IdTable AS t4)
LEFT JOIN EventMap ON t1.eventcode = EventMap.eventcode
LEFT JOIN Industries AS t2 ON t1.sectorasof = t2.IndNum
LEFT JOIN Industries AS t3 ON t1.sector = t3.IndNum
LEFT JOIN Industries AS t8 ON t1.oldsector = t8.IndNum
LEFT JOIN IndexNames AS t5 ON t1.oldmarket = t5.Market
LEFT JOIN IndexNames AS t6 ON t1.scale = t6.Scale
LEFT JOIN IndexNames AS t7 ON t1.oldscale = t7.Scale
WHERE (t1.market=1 OR t1.marketasof=1 OR (t1.oldmarket=1 AND t1.marketasof=""))
AND t1.effectivedate >= '20170630'
AND t1.effectivedate <= '20170703'
AND t1.Qcode = t4.Qcode
ORDER BY t1.effectivedate, t1.eventcode,t1.qcode
Don't mix legacy and new join syntax.
...
FROM dbo.AdvNoticeData as t1
JOIN dbo.IdTable as t4 ON t1.Qcode = t4.Qcode
LEFT JOIN dbo.EventMap on t1.EventCode = dbo.EventMap.EventCode
...
Modify your old JOIN syntax with an INNER JOIN
declare #symbol varchar(8) = '180460';
declare #sdate DATE = '20170630';
declare #edate DATE = '20170704';
IF #symbol = 'TSE00081'
BEGIN
SELECT * from dbo.IndexNames
END
ELSE
BEGIN
SELECT t1.qcode, t4.Name,t1.effectivedate, t1.publishdate, EventMap.Description, t1.SharesChanged, t1.FFW, t1.OldFFW,
IIF(t1.EventCode='SK',t6.IndexName,''), IIF(t1.EventCode='SK',t7.Indexname,''), IIF(t1.Market<>'',t5.IndexName,''), IIF(t3.NameEn<>'',t3.NameEn,t2.NameEn),
IIF(t1.OldSector<>'',t8.NameEn,''), IIF(t1.Allotment1<>0 AND t1.EventCode<>'05', t1.Allotment2/t1.Allotment1,''), t1.SharesUnit
FROM dbo.AdvNoticeData as t1
INNER JOIN dbo.IdTable as t4 ON t1.Qcode = t4.Qcode
LEFT JOIN dbo.EventMap on t1.EventCode = dbo.EventMap.EventCode
LEFT JOIN dbo.Industries as t2 on t1.SectorAsOf = t2.IndNum
LEFT JOIN dbo.Industries as t3 on t1.Sector = t3.IndNum
LEFT JOIN dbo.Industries as t8 on t1.OldSector = t8.IndNum
LEFT JOIN dbo.IndexNames as t5 on t1.OldMarket = t5.Market
LEFT JOIN dbo.IndexNames as t6 on t1.Scale = t6.Scale
LEFT JOIN dbo.IndexNames as t7 on t1.OldScale = t7.Scale
WHERE (t1.Market=1 or t1.MarketAsOf=1 or (t1.OldMarket=1 and t1.MarketAsOf=''))
and t1.EffectiveDate >= #sdate and t1.EffectiveDate <= #edate
ORDER BY t1.EffectiveDate, t1.EventCode, t1.Qcode
END
Related
I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.
The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...
I have created the following case statement to do some multiplication depending on the items sales unit of measure and for this example, even though I am declaring the SalesUoM Variable as Gallon, it is doing the math for both the gallons and the lbs.
declare #SalesUOM as nvarchar(30)
declare #drumqty as nvarchar(30)
Set #SalesUOM = 'GAL'
Set #drumqty = '3'
SELECT DISTINCT
Case
--- when #SalesUOM = 'DRUM' then ( #drumqty * T1.BaseQty )
-- when #SalesUOM = 'PALLET' then ( #drumqty * T4.BaseQty )
--when #SalesUOM = 'PAIL' then ( #drumqty * T6.BaseQty )
--when #SalesUOM = 'TOTE' then ( #drumqty * T8.BaseQty )
when #SalesUOM = 'LB' then ( #drumqty * T10.BaseQty )
When #SalesUOM = 'GAL' then (#drumQty * T12.BaseQty)
Else '0' End as 'Item Qty'
FROM OUGP T0
--INNER JOIN UGP1 T1 ON T0.[UgpEntry] = T1.[UgpEntry]
--INNER JOIN UGP1 T4 on T0.[UgpEntry] = T4.[UgpEntry]
--INNER JOIN UGP1 T6 on T0.[UgpEntry] = T6.[UgpEntry]
--INNER JOIN UGP1 T8 on T0.UgpEntry = T8.UgpEntry
inner JOIN UGP1 T10 on T0.UgpEntry = T10.UgpEntry
inner JOIN UGP1 T12 on T0.UgpEntry = T12.UgpEntry
--INNER JOIN OUOM T2 ON T0.[BaseUom] = T2.[UomEntry]
--Inner Join OUOM T3 on T1.[UomEntry] = T3.[UomEntry] AND T3.UOMCODE in ('DR-15', 'DR-30', 'DR-55')
--Inner Join OUOM T5 on T4.[UomEntry] = T5.[UomEntry] and T5.UOMCODE = 'PALLET'
--left Join OUOM T7 on T6.UoMEntry = T7.UomEntry and T7.UOMCODE = 'PAIL-5'
--left Join OUOM T9 on T8.UomEntry = T9.UomEntry AND T9.UomCode = 'TOTE'
Left Join OUOM T11 on T10.UomEntry = T11.UomEntry and T11.UomCode = 'LB'
Left Join OUOM T13 on T12.UomEntry = T13.UomEntry and T13.UomCode = 'GAL'
Left join OITM on T0.UgpCode = OITM.ItemCode
WHERE
OITM.ItemCode = '0000000'
because you are not filtering the result set on #SalesUOM in where clause or inner join.
T10 and T12 are pointing to the same table UGP1.
below are two ways that can resolve your problem
1. Add T11.UomCode = #SalesUOM And T13.UomCode = #SalesUOM in where clause
2. Replace below Statements
"Left Join OUOM T11 on T10.UomEntry = T11.UomEntry and T11.UomCode = 'LB'
Left Join OUOM T13 on T12.UomEntry = T13.UomEntry and T13.UomCode = 'GAL'"
with below statements
Inner Join OUOM T11 on T10.UomEntry = T11.UomEntry and T11.UomCode = #SalesUOM
I have a task to send a list of cost-centers(varchar) to the query and the query should provide data based on each input.
I have no understanding of dynamic SQL.
So I have a list of cost centers like 88115100, 88115200, 88115300......around 30.
declare #month integer
declare #month_2 integer
declare #startdate datetime
declare #enddate datetime
declare #costcenter varchar(20)
set #month_2= 3--/* t3.finncPriod=*/ '[%0]'
set #month=#month_2-1
set #costcenter='88115100'
set #startdate= '03/01/2019'--/*t0.docdate from oinm t0 where t0.docdate>=*/'[%1]'
set #enddate= '03/31/2019'--/*t0.docdate from oinm t0 where t0.docdate>=*/'[%2]'
select * from
(
select
t0.name+'-Budget' as 'toPivot',
t4.AcctCode as 'GLAccount',
t4.AcctName,
isnull(t2.DebLTotal,0) as 'value'
from obgs as t0
inner join obgt as t1 on t0.AbsId = t1.Instance
inner join bgt1 as t2
on t2.Instance = t1.Instance
and t2.AcctCode = t1.AcctCode
and t2.Line_ID = #month
inner join oact as t4 on t4.AcctCode = t2.AcctCode
where t0.name = #costcenter
union all
select
t0.name + '-Actual'as 't0Pivot',
t4.AcctCode as 'GLAccount',
t4.AcctName,
isnull(sum(debit-credit),0) as 'value'
from jdt1 as t3
left join oact t4 on t4.AcctCode = t3.Account
left join obgs t0 on t0.Name = t3.ProfitCode
left join obgt t1
on t1.Instance = t0.AbsId
and t4.AcctCode = t1.AcctCode
left join bgt1 as t2
on t1.Instance = t2.Instance
and t2.AcctCode = t1.AcctCode
and t2.line_ID = 2
where
t3.refdate between #startdate and #enddate
and t4.ExportCode is not null
and t0.name = #costcenter
group by
t0.name,
t4.AcctCode,
t4.AcctName
) as a
pivot
(
sum(a.value)
for a.topivot in
([88115100-Budget], [88115100-Actual])
)
as pivottable
Ok, so from what I can tell you probably want a stored procedure, and you're suggesting that it could/should be dynamic SQL. Now, you could do that, but the only time you need dynamic SQL is when you have to rewrite keywords depending on variables. You would have to do that with your code above - specifically the following bit:
pivot
(
sum(a.value)
for a.topivot in
([88115100-Budget], [88115100-Actual])
)
This is because [88115100-Budget] and [88115100-Actual] are keywords which depend on your variable (#costcenter). But there's no reason for them to be named like that in SQL! You're much better applying those names later, in whatever it is that you're sending this data to outside of SQL.
Instead, you probably want something like the following code:
CREATE PROCEDURE GetBudgetForCostCenter
#month integer = 2,
#month_2 integer = 3,
#startdate datetime = '03/01/2019',
#enddate datetime = '03/31/2019',
#costcenter varchar(20) = '88115100'
--you probably don't actually want the default values in here, but I've left them for demonstration.
AS
BEGIN
select * from
(
select
'Budget' as 'toPivot',
t4.AcctCode as 'GLAccount',
t4.AcctName,
isnull(t2.DebLTotal,0) as 'value'
from obgs as t0
inner join obgt as t1 on t0.AbsId = t1.Instance
inner join bgt1 as t2
on t2.Instance = t1.Instance
and t2.AcctCode = t1.AcctCode
and t2.Line_ID = #month
inner join oact as t4 on t4.AcctCode = t2.AcctCode
where t0.name = #costcenter
union all
select
'Actual'as 't0Pivot',
t4.AcctCode as 'GLAccount',
t4.AcctName,
isnull(sum(debit-credit),0) as 'value'
from jdt1 as t3
left join oact t4 on t4.AcctCode = t3.Account
left join obgs t0 on t0.Name = t3.ProfitCode
left join obgt t1
on t1.Instance = t0.AbsId
and t4.AcctCode = t1.AcctCode
left join bgt1 as t2
on t1.Instance = t2.Instance
and t2.AcctCode = t1.AcctCode
and t2.line_ID = 2
where
t3.refdate between #startdate and #enddate
and t4.ExportCode is not null
and t0.name = #costcenter
group by
t0.name,
t4.AcctCode,
t4.AcctName
) as a
pivot
(
sum(a.value)
for a.topivot in
([Budget], [Actual])
)
as pivottable
END
Note that I've changed your columns from 88115100-Budget and 88115100-Actual to just be Budget and Actual. This means that you can avoid using dynamic SQL which is something you should always aim to do.
This should now be able to be called via something like
exec GetBudgetForCostCenter #month = 2, #month_2 = 3, #startdate = '03/01/2019', #enddate = '03/31/2019', #costcenter = '88115100'
Disclaimer: I can't be bothered testing the syntax more than with the built-in syntax highlighting as it would require creating a new database and a lot of new objects, so sorry if there's any typos in there.
I am trying to read my previous value of "OPENSEATING" and store it into the variable #OPENSEATING. For the second query I want it to check first the value of #OPENSEATING if match condition do the below query.
i believe my declaration is correct, is there any syntax error?
DECLARE #OPENSEATING AS BIT
SELECT
'2019-01-31' AS DATE,
(SELECT
THEATRES.OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING) AS #OPENSEATING,
IF(#OPENSEATING =0)
BEGIN
(SELECT
(THEATRES.CAPACITY - COUNT(TICKET_ITEMS.ID)) AS SEATREMAINING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES ON THEATRES.ID = SHOWTIMES.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND SHOWTIMES.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
SHOWTIMES.ID = A.ID
GROUP BY THEATRES.CAPACITY) AS REMAININGSEAT
END
ELSE IF(#OPENSEATING =1)
BEGIN
(SELECT
(THEATRES.CAPACITY - COUNT(TICKET_ITEMS.ID)) AS SEATREMAINING
FROM
SHOWTIMES LEFT JOIN THEATRES ON THEATRES.ID = SHOWTIMES.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND SHOWTIMES.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
SHOWTIMES.ID = A.ID
GROUP BY THEATRES.CAPACITY) AS REMAININGSEAT
END
SHOWSCHEDULES.ID AS SHOWSCHEDULE_ID,
A.ID AS SHOWTIME_ID,
A.THEATREID
FROM
SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
ORDER BY SHOWBEGINTIME_24 ASC
;
AS SUGGESTED BY #Slava Murygin I tried creating CTE TABLE as below but even this is showing error, what is wrong with my simple cte table. The inner query is working fine.
WITH cte_name (OPENSEATING) AS (
SELECT
(SELECT
THEATRES.OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING) AS OPENSEATING
FROM
SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
)
I have made changes to your CTE as:
WITH cte_name (OPENSEATING) AS (
SELECT
THEATRES.OPENSEATING as OPENSEATING
FROM
SEAT LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
WHERE
B.ID = A.ID
GROUP BY THEATRES.OPENSEATING
)
select openseating from
cte_name, SHOWSCHEDULES JOIN SHOWTIMES AS A ON SHOWSCHEDULES.ID = A.SHOWSCHEDULEID
JOIN SHOWLANGUAGES ON A.SHOWLANGUAGEID = SHOWLANGUAGES.ID
WHERE
'2019-01-31' BETWEEN CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), SHOWSCHEDULES.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
You can't do that in one query. You have to get variable in the first query and then use it in IF statement.
If you WANT to use ONLY ONE statement then you have to use CTEs, but it will hide the logic and will be hard to debug.
It might be something like this, but no guarantee it will work, because I have no idea about your business logic and data behind:
;WITH OPENSEATING as (
SELECT THEATRES.OPENSEATING, B.ID
FROM SEAT
LEFT JOIN THEATRES ON SEAT.ROOMID = THEATRES.ID
LEFT JOIN SHOWTIMES AS B ON THEATRES.ID = B.THEATREID
LEFT JOIN TICKET_ITEMS ON TICKET_ITEMS.SEATNO = SEAT.SEATNO AND B.ID = TICKET_ITEMS.SHOWTIMESID
GROUP BY THEATRES.OPENSEATING),
REMAININGSEAT0 as (
SELECT st.ID, (t.CAPACITY - COUNT(ti.ID)) AS SEATREMAINING
FROM SEAT as s
LEFT JOIN THEATRES as t ON s.ROOMID = t.ID
LEFT JOIN SHOWTIMES as st ON t.ID = st.THEATREID
LEFT JOIN TICKET_ITEMS ON ti.SEATNO = s.SEATNO AND st.ID = ti.SHOWTIMESID
GROUP BY t.CAPACITY),
REMAININGSEAT1 as (
SELECT st.ID, (t.CAPACITY - COUNT(ti.ID)) AS SEATREMAINING
FROM SHOWTIMES as st
LEFT JOIN THEATRES as t ON t.ID = st.THEATREID
LEFT JOIN SEAT as s ON s.ROOMID = t.ID
LEFT JOIN TICKET_ITEMS as ti ON ti.SEATNO = s.SEATNO AND st.ID = ti.SHOWTIMESID
GROUP BY t.CAPACITY)
SELECT '2019-01-31' AS DATE
, ss.ID AS SHOWSCHEDULE_ID
, A.ID AS SHOWTIME_ID
, A.THEATREID
, SEATREMAINING = CASE OS.OPENSEATING WHEN 0 THEN RS0.SEATREMAINING ELSE RS1.SEATREMAINING END
FROM SHOWSCHEDULES as ss
INNER JOIN SHOWTIMES AS A ON ss.ID = A.SHOWSCHEDULEID
INNER JOIN SHOWLANGUAGES as SL ON A.SHOWLANGUAGEID = SL.ID
INNER JOIN OPENSEATING as OS ON OS.ID = A.ID
LEFT JOIN REMAININGSEAT0 as RS0 ON RS0.ID = A.ID
LEFT JOIN REMAININGSEAT1 as RS1 ON RS1.ID = A.ID
WHERE '2019-01-31' BETWEEN CONVERT(VARCHAR(10), ss.SHOWFROMDATE, 20) AND CONVERT(VARCHAR(10), ss.SHOWTODATE, 20)
AND CONVERT(VARCHAR(8), getdate(), 8) < CONVERT(VARCHAR(10), A.SHOWENDTIME,8)
ORDER BY SHOWBEGINTIME_24 ASC;
I have three queries,query 1 and query 2 have to be inner joined on Customer_number
Resultant output from query1 and query2 will be further inner joined on 3 keys customer_number,account_number,bank_number.
Can anyone help me to write the queries for these.I am not able to derive it.
Thanks in advance,
Bhaskar
Query1 :
SELECT
CUST.BANK_NUMBER as CUSTBANKNUMBER,
CUST.CUSTOMER_NUMBER,
CUST.DATE_DECEASE,
FROM
SIGN_LND.T_CUSTOMER_MASTER_FILE_LND CUST
LEFT OUTER JOIN
SIGN_LND.T_CUST_USER_DEF_FIELDS_LND USER_DEF
ON (CUST.CUSTOMER_NUMBER = USER_DEF.CUSTOMER_NUMBER AND CUST.EFF_DT = USER_DEF.EFF_DT)
WHERE
CUST.EFF_DT = TO_DATE('2015-01-22','YYYY-MM-DD')
Query 2 :
SELECT
S.CUSTOMER_NUMBER,
S.ALIAS_ACCOUNT_NBR,
M.BANK_NUMBER,
M.ACCOUNT_NUMBER,
M.PRODUCT_CODE,
M.APPLICATION_NUMBER,
M.APPL_ID
FROM
(
SELECT T1.BANK_NUMBER,
T1.ACCOUNT_NUMBER,
T1.PRODUCT_CODE,
CAST (NULL AS VARCHAR(5)) AS SUB_PRODUCT_CODE,
T1.APPLICATION_NUMBER,
T1.APPL_ID
FROM SIGN_LND.T_LOAN_MASTER_FILE_LND T1
INNER JOIN SIGN_LND.T_LOAN_PRODUCT_DEFINITION_LND T2
ON T1.BANK_NUMBER = T2.BANK_NUMBER
AND T1.PRODUCT_CODE = T2.PRODUCT_CODE
AND T1.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
AND T2.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
WHERE T1.PRODUCT_CODE IS NOT NULL
AND T1.DATE_OPEN IS NOT NULL
UNION ALL
SELECT T1.BANK_NUMBER,
T1.ACCOUNT_NUMBER,
T1.PRODUCT_CODE,
T1.PRODUCT_CODE AS SUB_PRODUCT_CODE,
T1.APPLICATION_NUMBER,
T1.APPL_ID
FROM SIGN_LND.T_TA_MASTER_FILE_LND T1
INNER JOIN SIGN_LND.T_TA_PRODUCT_DEFINITION_LND T2
ON T1.BANK_NUMBER = T2.BANK_NUMBER
AND T1.PRODUCT_CODE = T2.PRODUCT_CODE
AND T1.ACCOUNT_TYPE = T2.ACCOUNT_TYPE
AND T1.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
AND T2.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
LEFT JOIN SIGN_LND.T_BONUS_INT_MASTER_FILE_LND T3
ON T1.ACCOUNT_NUMBER = T3.ACCOUNT_NUMBER
AND T1.BANK_NUMBER = T3.BANK_NUMBER
AND T3.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
WHERE T1.PRODUCT_CODE IS NOT NULL
AND T1.ACCOUNT_STATUS_CODE IS NOT NULL
AND T1.DATE_OPEN IS NOT NULL
UNION ALL
SELECT T1.BANK_NUMBER,
T1.ACCOUNT_NUMBER,
T1.PRODUCT_CODE,
T1.PRODUCT_CODE AS SUB_PRODUCT_CODE,
T1.APPLICATION_NUMBER,
T1.APPL_ID,
FROM SIGN_LND.T_TIME_MASTER_FILE_LND T1
INNER JOIN SIGN_LND.T_TM_PRODUCT_DEFINITION_LND T2
ON T1.BANK_NUMBER = T2.BANK_NUMBER
AND T1.PRODUCT_CODE = T2.PRODUCT_CODE
AND T1.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
AND T2.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
LEFT JOIN SIGN_LND.T_BONUS_INT_MASTER_FILE_LND T3
ON T1.ACCOUNT_NUMBER = T3.ACCOUNT_NUMBER
AND T1.BANK_NUMBER = T3.BANK_NUMBER
AND T3.EFF_DT=TO_DATE('2015-01-22','YYYY-MM-DD')
WHERE T1.PRODUCT_CODE IS NOT NULL
AND T1.ACCOUNT_STATUS_CODE IS NOT NULL
AND T1.DATE_OPEN IS NOT NULL
)M
INNER JOIN
(
SELECT
T1.ACCOUNT_NUMBER,
T1.CUSTOMER_NUMBER,
T1.RELATIONSHIP ,
T2.ALIAS_ACCOUNT_NBR,
T2.APPLICATION_NUMBER
FROM SIGN_LND.T_CUSTOMER_CROSS_REF_LND T1
INNER JOIN
SIGN_LND.T_ALIAS_ACCT_NBR_CRSS_REF_LND T2
ON T1.ACCOUNT_NUMBER=T2.ACCOUNT_NUMBER
WHERE ALIAS_ACCOUNT_NBR_TYPE='UK'
GROUP BY T1.ACCOUNT_NUMBER,
T1.CUSTOMER_NUMBER,
T1.RELATIONSHIP ,
T2.ALIAS_ACCOUNT_NBR,
T2.APPLICATION_NUMBER
)S
ON M.ACCOUNT_NUMBER=S.ACCOUNT_NUMBER
AND
M.APPLICATION_NUMBER=S.APPLICATION_NUMBER
)
Query3:
SELECT
SPLIT.BANK_NUMBER,
SPLIT.CUSTOMER_NUMBER,
SPLIT.DATE_MOVING_IN,
SPLIT.TITLE,
SPLIT.FIRST_NAME,
SPLIT.SECOND_NAME,
SPLIT.SURNAME,
SPLIT.CURR_APT_NUMBER_UPS,
SPLIT.CURR_HOUSE_NAME_UPS,
SPLIT.CURR_HOUSE_NBR,
SPLIT.CURR_STREET_UPS,
SPLIT.CURR_DISTRICT_UPS,
SPLIT.CURR_POST_TOWN_UPS,
SPLIT.POSTAL_CODE,
SPLIT.CURR_COUNTRY,
CUST_EXT.LOYALTY_CARD_NBR,
XREF.ACCOUNT_NUMBER,
XREF.RELATIONSHIP as RELATIONSHIP_RB,
RB_ALIAS_XREF.APPL_ID as RBXREFAPPID,RB_ALIAS_XREF.ALIAS_ACCOUNT_NBR AS ALIAS_ACCOUNT_NBR_RB,
PROD_OFFER.DATE_CLOSE
FROM
(
SIGN_LND.T_CIF_SPLIT_NAME_ADDR_UPS_LND SPLIT
LEFT OUTER JOIN
SIGN_LND.T_CUST_MASTER_EXTENSION_LND CUST_EXT
ON (SPLIT.CUSTOMER_NUMBER = CUST_EXT.CUSTOMER_NUMBER AND SPLIT.EFF_DT = CUST_EXT.EFF_DT)
)
LEFT OUTER JOIN
(
SIGN_LND.T_CUSTOMER_CROSS_REF_LND XREF
LEFT OUTER JOIN
(
SELECT * FROM SIGN_LND.T_ALIAS_ACCT_NBR_CRSS_REF_LND WHERE EFF_DT = TO_DATE('2015-01-22','YYYY-MM-DD') AND ALIAS_ACCOUNT_NBR_TYPE = 'RB'
) RB_ALIAS_XREF
ON (XREF.ACCOUNT_NUMBER = RB_ALIAS_XREF.ACCOUNT_NUMBER AND XREF.EFF_DT = RB_ALIAS_XREF.EFF_DT)
LEFT OUTER JOIN
SIGN_LND.T_PRODUCT_OFFER_PURCHASE_LND PROD_OFFER
ON (XREF.BANK_NUMBER = PROD_OFFER.BANK_NUMBER AND XREF.ACCOUNT_NUMBER = PROD_OFFER.ACCOUNT_NUMBER AND XREF.EFF_DT = PROD_OFFER.EFF_DT)
)
ON (SPLIT.CUSTOMER_NUMBER = XREF.CUSTOMER_NUMBER AND SPLIT.EFF_DT = XREF.EFF_DT)
WHERE SPLIT.EFF_DT = TO_DATE('2015-01-22','YYYY-MM-DD')``
This should work
WITH query1 as
(your query 1 code),
query2 as
(you query 2 code),
query3 as
(your query 3 code)
select * from query1
join query2 on query1.Customer_number=query2.Customer_number
join query3 on query3.customer_number=query2.customer_number
and query3.account_number=query2.account_number
and query3.bank_number=query2.bank_number