Limiting a query by MTD, Prior month, etc. to SSRS - sql
I am trying to form a report out of the following query, and the issue I am having is: how do I get it to make a structure where I can call it in SSRS, say calling MTF, PMonth, PPMonth as a "Type" choice, when I put it into SSRS, I want MTD, PMonth and PPMonth to appear in the report as separate entities.
-- ResWare.dbo.rptClosingPipeline3
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DECLARE #today varchar(20)
SET #today = Convert(varchar, GetDate(), 101)
DECLARE #startdate datetime
SET #startdate = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #enddate datetime --today at midnight. first moment of the day
SET #enddate = dbo.GetUTCDateTimeFunc(#today)--
DECLARE #MTD datetime
SET #MTD = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #PMonth datetime
SET #PMonth = dbo.GetUTCDateTimeFunc(DateAdd(m, -1, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))
DECLARE #PMonthEnd datetime
SET #PMonthEnd = dbo.GetUTCDateTimeFunc(DateAdd(m, 0, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
DECLARE #PPMonth datetime
SET #PPMonth = dbo.GetUTCDateTimeFunc(DateAdd(m, -2, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))
DECLARE #PPMonthEnd datetime
SET #PPMonthEnd = dbo.GetUTCDateTimeFunc(DateAdd(m, -1, convert(datetime, convert(char(8), current_timestamp, 112)) - day(current_timestamp) + 1))--
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #startdate
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #startdate
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #MTD
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #MTD
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PMonth
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PMonth
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
UNION ALL
SELECT FM.FileNumber AS FileNumber,
ISNULL(IU.TEAMNAME,'') AS Closer,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate) AS Scheduled,
dbo.GetLocalDateTimeFunc(FM.DisbursementDate) AS DisbursementDate,
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate) AS EstSettlementDate,
CASE WHEN EXISTS (SELECT * FROM FilePartnerRel FPR1
WHERE FPR1.PartnerTypeID = 10033 AND FPR1.FileID = FM.FileID)
THEN P.State+'-(W)'
ELSE P.State END AS State,
ISNULL(P.StreetNumber,'')+' '+ISNULL(P.StreetDirection,'')+' '+ISNULL(P.StreetName,'')+' '+ISNULL(P.Unit,'')AS PropertyAddress,
S.Name,
(SELECT CONVERT(varchar(7000),Body) FROM Note WHERE NoteID =
(Select MAX(N.NoteID)
FROM Note N
JOIN FileActions A1 ON A1.FileID=FM.FileID
AND A1.ActionDefID IN (141,386,306)
JOIN FileActionNoteRel AN ON AN.FileActionsID=A1.FileActionsID
AND N.NoteID = AN.NoteID)) AS Note,
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
JOIN Coordinator C1 ON C1.FileID = FA1.FileID
AND C1.CoordinatorTypeID IN (2, 6)
AND C1.CoordinatorID = C.CoordinatorID
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PPMonth
AND FM1.StatusID != 8),
(SELECT COUNT(DISTINCT FA1.FileID) FROM FileActions FA1
JOIN FileMain FM1 ON FM1.FileID = FA1.FileID
AND FM1.FileNumber NOT LIKE 'PA-%'
WHERE FA1.ActionDefID IN (61,315,393)
AND FA1.ReceivedDate >= #PPMonth
AND FM1.StatusID != 8) AS TotalDisb
, TRT.Name CurativeItem
, SD.CommitmentEffDate
FROM FileMain FM
JOIN ActionListTransactionType ALTT ON ALTT.ActionListTransactionTypeID = FM.ActionListTransactionTypeID
JOIN ActionListProductType ALPT ON ALPT.ActionListProductTypeID = FM.ActionListProductTypeID
JOIN Coordinator C ON C.FileID = FM.FileID
AND C.CoordinatorTypeID IN (2)
LEFT JOIN FilePartnerRel FPR ON FPR.FileID = FM.FileID
AND FPR.PartnerTypeID = 5
JOIN Property P ON P.FileID = FM.FileID
LEFT JOIN PartnerCompany PC ON PC.PartnerCompanyID = FPR.PartnerCompanyID
JOIN PartnerCompany PC1 ON PC1.PartnerCompanyID = FM.ClientID
JOIN TEAM IU ON IU.TEAMID = C.CoordinatorID
JOIN Status S ON S.StatusID = FM.StatusID
LEFT JOIN TitleReview TR ON TR.FileID = Fm.FileID
AND (TR.InternalClear IS NULL OR TR.InternalClear = 0)
LEFT JOIN TitleReviewType TRT ON TRT.TitleReviewTypeID = TR.TitleReviewTypeID
LEFT JOIN SearchData SD ON SD.FileID = FM.FileID
WHERE FM.OfficeID = 1
AND FM.FileNumber NOT LIKE 'PA-%'
AND FM.StatusID IN (2,4,5,10,11,14,15,18)
GROUP BY FM.FileNumber,
PC1.Name,
PC.Name,
ISNULL(IU.TEAMNAME,''),
ALTT.Name +': '+ALPT.DisplayName,
dbo.GetLocalDateTimeFunc(FM.ActualSettlementDate),
dbo.GetLocalDateTimeFunc(FM.DisbursementDate),
dbo.GetLocalDateTimeFunc(FM.EstSettlementDate),
FM.FileID,
P.State,
P.StreetNumber,
P.StreetDirection,
P.StreetName,
P.Unit,
S.Name,
FM.EstSettlementDate,
C.CoordinatorID,
TRT.Name,
SD.CommitmentEffDate
Option 1:
Add a hard-coded column to your query as follows:
SELECT ...
, 'StartDt' as Period
From QUERY1
UNION ALL
SELECT ...
, 'MTD' as Period
FROM QUERY2
UNION ALL
SELECT ...
, 'Pmonth' as Period
FROM QUERY3
Then I would add a report parameter "#filter" (or whatever name you like) with the 'StartDt', 'MTD', 'Pmonth', etc. as its available values. Enable multiple values and ensure it is a text parameter.
Then set each section of your report's filter to see if the "Period" column matches the parameter.value of the filter.
Option 2:
Add a report parameter #filter as above.
Create a table variable and insert the values passed in by the filter parameter into it.
Use a Case When to pass a 1 or 0 back to SSRS in the final column, representing whether that section should be visible or not.
,Period = CASE
WHEN 'StartDt' IN (SELECT * FROM #table) then 1
ELSE 0
END
Then set your filter to only include data with a period value of 1 and to set the visibility of the report sections accordingly.
Related
SQL convert date when select
When selecting the data, I want the document date (belgetarihi) format to be just like the due date (vadetarihi). How to convert? Please help SELECT ICE_ODEMEBASLIK.*, ORT_DOSYALAR_kayitdamga AS DSY_kayitdamga, HP.ID HP_ID, HP.planadi HP_planadi, KP.ID KP_ID, KP.planadi KP_planadi, ICE_CARIBANKA.ID CBANKA_ID, ICE_CARIBANKA.kod CBANKA_kod, ICE_CARIBANKA.hesapnr CBANKA_hesapnr, ICE_CARIBANKA.subenr CBANKA_subenr, ICE_CARIBANKA.subeadi CBANKA_subeadi FROM ICE_ODEMEBASLIK WITH (NOLOCK) LEFT JOIN ORT_PLAN AS HP WITH (NOLOCK) ON ICE_ODEMEBASLIK.plankod = HP.plankod LEFT JOIN ORT_PLAN AS KP WITH (NOLOCK) ON ICE_ODEMEBASLIK.karsiplankod = KP.plankod LEFT JOIN (SELECT DISTINCT ORT_DOSYALAR.kayitdamga AS ORT_DOSYALAR_kayitdamga FROM ORT_DOSYALAR WITH (NOLOCK) WHERE ORT_DOSYALAR.tablo = 6) AS DOSYA ON ICE_ODEMEBASLIK.kayitdamga = ORT_DOSYALAR_kayitdamga LEFT JOIN ICE_CARIBANKA WITH (NOLOCK) ON ICE_CARIBANKA.kayitdamga = ICE_ODEMEBASLIK.UQ_caribanka WHERE 1 = 1 AND ICE_ODEMEBASLIK.IOdurum = -1 AND ICE_ODEMEBASLIK.odemetipi = 1 AND ICE_ODEMEBASLIK.pin = 0 AND ICE_ODEMEBASLIK.belgetarihi >= CONVERT(DATETIME, '01.01.2022', 103) AND ICE_ODEMEBASLIK.belgetarihi < CONVERT(DATETIME, '01.01.2023', 103) ORDER BY CONVERT(DATE, ICE_ODEMEBASLIK.belgetarihi, 103), ICE_ODEMEBASLIK.IDfisbaslik,ICE_ODEMEBASLIK.vadetarihi here image
How to add IF ELSE by referencing to previous value
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;
SQL / SSRS: The multi-part identifier " " could not be bound
Working on a report that currently is in two columns on two datasets, an dam trying to combine the datasets into one single query. When I do the following query, I get The multi-part identifier "fa.InternalUserID" could not be bound. --TST Group SELECT A.AuditID, A.FileID, A.Description, A.UserID, IU.FirstName + ' ' + IU.LastName AS UserName, FM.FileNumber, SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime', CONVERT(VARCHAR(10), A.Date, 101) AS 'Date', CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime', COUNT(FA.FileActionsID) AS ActionCount FROM FileMain fm INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID JOIN FileActions FA on FA.FileID = FM.FileID LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID WHERE (FM.OfficeID = 1) AND (A.Description = 'File Opened' OR A.Description = 'File Closed') AND (A.Date >= GETDATE() - 2) AND (IU.InternalUserID IN ( --ID's go here ) ) ORDER BY UserName, A.AuditID Here are the original two queries I am combining: --TST Group SELECT A.AuditID, A.FileID, A.Description, A.UserID, IU.FirstName + ' ' + IU.LastName AS UserName, FM.FileNumber, SWITCHOFFSET(CONVERT(datetimeoffset, A.Date),'-05:00') AS 'LocalDateTime', CONVERT(VARCHAR(10), A.Date, 101) AS 'Date', CONVERT(VARCHAR(10), A.Date, 14) AS 'UnadjustedTime', COUNT(FA.FileActionsID) AS ActionCount FROM Audit AS A INNER JOIN InternalUser AS IU ON A.UserID = IU.InternalUserID LEFT OUTER JOIN FileMain AS FM ON A.FileID = FM.FileID WHERE (FM.OfficeID = 1) AND (A.Description = 'File Opened' OR A.Description = 'File Closed') AND (A.Date >= GETDATE() - 2) AND (IU.InternalUserID IN ( --ID's Go here ) ) ORDER BY UserName, A.AuditID and SELECT IU.FirstName AS NAME, COUNT(FA.FileActionsID) AS ActionCount FROM FileActions AS FA INNER JOIN InternalUser AS IU ON FA.ReceivedUserID = IU.InternalUserID WHERE (FA.ReceivedDate > GETDATE() - 0) AND (FA.ReceivedUserID IN ( --ID's go here ) ) GROUP BY IU.FirstName
You have your joins in the wrong order. Currently you are trying to join InternalUser and FileActions when you've only mentioned FileMain and InternalUser (in that order) - you can't specify a condition against a table that hasn't been introduced to the join yet: FROM FileMain fm INNER JOIN InternalUser AS IU ON fa.InternalUserID = IU.InternalUserID JOIN FileActions FA on FA.FileID = FM.FileID LEFT OUTER JOIN Audit AS A ON A.FileID = FM.FileID Should be (with obligatory schema prefixes added): FROM dbo.FileMain fm INNER JOIN dbo.FileActions FA on FA.FileID = FM.FileID INNER JOIN dbo.InternalUser AS IU ON FA.InternalUserID = IU.InternalUserID LEFT OUTER JOIN dbo.Audit AS A ON A.FileID = FM.FileID
sql server using where criteria for multiple values being passed
I am trying to pass from 1 to 10 criterias to a stored procedure that uses a select statement below in this procedure below: ALTER PROCEDURE [dbo].[Original_Docs] #Cat varchar(255), #docType VARCHAR(255), #IdNo VARCHAR(50) AS BEGIN SELECT d4.id as DOCUMENT_ID, c.name as Category, dt.name as Document_Type, mv1.value as GUIDELINE_MASTER, mv2.value as ID_NUMBER, mv3.value as [DATE], mv4.value as DESCRIPTION, mv5.value AS BUDGET_NUM, mv6.value as STATUS, mv7.value AS [CLOSED DATE], mv8.value AS REPORT_TYPE FROM Documents d4 JOIN ( SELECT d2.id FROM Documents d2 JOIN ( SELECT d.fileStoreId, MIN(d.createdDate) as CreatedDate FROM Documents d JOIN FileStores fs ON d.fileStoreId = fs.id WHERE fs.shared = 1 AND d.dateDeleted IS NULL GROUP BY d.fileStoreId ) AS f ON d2.fileStoreId = f.fileStoreId AND d2.createdDate = f.CreatedDate UNION SELECT d3.id FROM Documents d3 JOIN FileStores fs2 ON d3.fileStoreId = fs2.id WHERE fs2.shared = 0 AND d3.dateDeleted IS NULL ) AS f2 ON f2.id = d4.id JOIN DocumentTypes dt ON d4.documentTypeId = dt.id JOIN Categories c ON dt.categoryId = c.id LEFT OUTER JOIN mv_guideline_master mv1 ON d4.id = mv1.documentId LEFT OUTER JOIN mv_id_number mv2 ON d4.id = mv2.documentId LEFT OUTER JOIN mv_date mv3 ON d4.id = mv3.documentId LEFT OUTER JOIN mv_description mv4 ON d4.id = mv4.documentId LEFT OUTER JOIN mv_budgetnum mv5 ON d4.id = mv5.documentId LEFT OUTER JOIN mv_status mv6 ON d4.id = mv6.documentId LEFT OUTER JOIN mv_closed_date mv7 ON d4.id = mv7.documentId LEFT OUTER JOIN mv_report_type mv8 ON d4.id = mv8.documentId WHERE c.name = #Cat AND (dt.name = #docType OR mv2.value = #IdNo) ORDER BY mv1.value I will need to add the rest of the other criteria after I figure out how to do it with 3 criteria. In the where clause, I am passing parameters #Cat, #docType, and #IdNo. how do I query using these criteria with the one of these being filled in with the other one or 2 blank? Or if all of them where passed in or if only 2 were passed in. If I use AND then it doesn't work or if I use OR between the criteria, it will bring back the wrong result. Do I need Parens somewhere for it to work? thanks!
Not sure I follow exactly, if each variable can be NULL: WHERE (c.name = #Cat OR #Cat IS NULL) AND ((dt.name = #docType OR #docType IS NULL) OR (mv2.value = #IdNo OR #IdNo IS NULL)) or if blank: WHERE (c.name = #Cat OR #Cat = '') AND ((dt.name = #docType OR #docType = '') OR (mv2.value = #IdNo OR #IdNo = ''))
Order By Case multiple fields
The code below (and numerous codes like it) continues to return blanks. Basically, if LaborCode = '01 - SC' then it should sort by JobSite, LaborCode, and Schedule (the exact date) If it's NOT 01 - SC, it should sort by JobSite, LaborCode, and DayNo (the day of the week) Select Distinct Agreements.AgrmntID, Agreements.Description, Agreements.Status, JobSites.SiteName, JobSites.Address2, JobSites.City, Customers.CustName, Customers.CompanyName, LaborCodeTypes.RepairCode As LaborCode, Schedule = Case LaborCodeTypes.RepairCode When '01 - SC' Then Left(Convert(varchar,AgreementSchedules.SchedDate,110), 10) Else DateName(dw, AgreementSchedules.SchedDate) End, Employees1.EmpName As Vendor, Employees.EmpName As [Area Manager], DatePart(dw, AgreementSchedules.SchedDate) As DayNo From Agreements Inner Join Customers On Agreements.CustID = Customers.CustID Inner Join AgreementSchedules On Agreements.AgrmntID = AgreementSchedules.AgrmntID Inner Join JobSites On Agreements.CustSiteID = JobSites.CustSiteID Left Outer Join LaborCodeTypes On AgreementSchedules.RepairID = LaborCodeTypes.RepairID Left Outer Join Employees On AgreementSchedules.FormanEmpID = Employees.EmployeeID Left Join WorkOrderSchedules On WorkOrderSchedules.ScheduleID = AgreementSchedules.ScheduleID And AgreementSchedules.ScheduleID = WorkOrderSchedules.ScheduleID Left Join WorkOrderScheduleTechs On WorkOrderSchedules.ScheduleID = WorkOrderScheduleTechs.ScheduleID Left Join Employees Employees1 On WorkOrderScheduleTechs.EmployeeID = Employees1.EmployeeID Where Agreements.Status = 2 And LaborCodeTypes.RepairCode <> 'Vendor Bill' And Month(AgreementSchedules.SchedDate) = Month(GetDate()) Order By Case When [LaborCodeTypes.RepairCode] In ('01 - SC') Then JobSites.SiteName + LaborCodeTypes.RepairCode + Schedule Else JobSites.SiteName + LaborCodeTypes.RepairCode + DayNo End Thank you for your help!!
Try this: ORDER BY JobSites.SiteName, LaborCodeTypes.RepairCode, CASE WHEN LaborCodeTypes.RepairCode IN ('01 - SC') THEN Schedule ELSE DayNo END
Okay, in SQL Server: CREATE PROCEDURE dbo.Agreements_GetList AS BEGIN SET NOCOUNT ON; SELECT DISTINCT a.AgrmntID, a.Description, a.Status, js.SiteName, js.Address2, js.City, c.CustName, c.CompanyName, LaborCode = lct.RepairCode, Schedule = CASE lct.RepairCode WHEN '01 - SC' THEN CONVERT(CHAR(10), aSch.SchedDate, 110) --------------------^^^ much better than LEFT and not specifying length ELSE DATENAME(WEEKDAY, aSch.SchedDate) END, Vendor = e2.EmpName, [Area Manager] = e1.EmpName, DayNo = CONVERT(CHAR(1), DATEPART(WEEKDAY, aSch.SchedDate)) --------^^^ this convert is important FROM dbo.Agreements AS a INNER JOIN dbo.Customers AS c ON a.CustID = c.CustID INNER JOIN dbo.AgreementSchedules AS aSch ON a.AgrmntID = aSch.AgrmntID INNER JOIN dbo.JobSites AS js ON a.CustSiteID = js.CustSiteID LEFT OUTER JOIN dbo.LaborCodeTypes AS lct ON aSch.RepairID = lct.RepairID LEFT OUTER JOIN dbo.Employees AS e1 ON aSch.FormanEmpID = e1.EmployeeID LEFT OUTER JOIN dbo.WorkOrderSchedules AS w ON w.ScheduleID = aSch.ScheduleID LEFT OUTER JOIN dbo.WorkOrderScheduleTechs AS wt ON w.ScheduleID = wt.ScheduleID LEFT OUTER JOIN dbo.Employees AS e2 ON wt.EmployeeID = e2.EmployeeID WHERE a.Status = 2 AND lct.RepairCode <> 'Vendor Bill' AND aSch.SchedDate >= DATEADD(MONTH, 0, DATEDIFF(MONTH, 0, GETDATE())) AND aSch.SchedDate < DATEADD(MONTH, 1, DATEDIFF(MONTH, 0, GETDATE())) ORDER BY js.SiteName, lct.RepairCode, CASE WHEN lct.RepairCode = '01 - SC' THEN js.SiteName ELSE DayNo END; END GO Now I have absolutely no knowledge of your application, so you will have to figure out how to call a stored procedure from it instead of embedding SQL.