0 Results Effecting Entire Query - sql

I was wondering if there is a way to make a results from a JOIN of a subquery result a predefined entry.
The query below pulls in the MAX(ReceiveDate) for the uniqueID JobNo. However, if nothing has been received the entire result will not show up. There are several other joins that could have data.
--***SUB QUERY (Receiver)
JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo
The query will ultimately pull in data from purchase orders, result the most recent date, and the receiver with its most recent date based on the JobNo.
If nothing is received then result 'Whatever' or NULL. Anything.
The entire query is below:
DECLARE #now DATETIME
DECLARE #90daysago DATETIME
SET #now = GETDATE()
SET #90daysago = DATEADD(day, -90, #now)
;with cte as
(
SELECT
o.PartNo,
o.JobNo,
ord.DateEnt as oDateEnt,
por.MAXPONum,
po.DateEnt as poDateEnt,
tt.MAXtt,
r.ReceiveDate,
CASE
WHEN po.DateEnt >= r.ReceiveDate AND po.DateEnt >= tt.MAXtt THEN cast(po.DateEnt as DATE)
WHEN r.ReceiveDate >= po.DateEnt AND r.ReceiveDate >= tt.MAXtt THEN cast(r.ReceiveDate as DATE)
WHEN tt.MAXtt >= po.DateEnt AND tt.MAXtt >= r.ReceiveDate THEN cast(tt.MAXtt as DATE)
ELSE po.DateEnt
END AS MostRecentDate,
POProrate.TotalCost,
WIPProrate.WIPProrateCost,
(POProrate.TotalCost+WIPProrate.WIPProrateCost) as ProratedCost,
(ROUND(cast((o.QtyToMake - o.QtyShipped2Stock) as FLOAT)/o.QtyToMake,3))*(POProrate.TotalCost+WIPProrate.WIPProrateCost) as TotalProratedCost,
ROW_NUMBER() OVER(PARTITION BY o.JobNo ORDER BY tt.MAXtt DESC) as RowNum
FROM
--***MAIN QUERY (OrderDet)***
OrderDet as o
--***SUB QUERY (Order)***
JOIN
(
SELECT
cast(DateEnt as DATE) as DateEnt,
OrderNo
FROM
Orders
) ord
ON ord.OrderNo = o.OrderNo
--***SUB QUERY (POReleases)***
JOIN
(
SELECT
MAX(PONum) as MAXPONum,
JobNo
FROM
POReleases
GROUP BY
JobNo
) por
ON por.JobNo = o.JobNo
--***SUB QUERY (PO)***
JOIN
(
SELECT
PONum,
cast(DateEnt as DATE) as DateEnt
FROM
PO
) po
ON po.PONum = por.MAXPONum
--***SUB QUERY (TimeTicketDet)
JOIN
(
SELECT MAX(CAST(TicketDate as DATE)) as MaxTT,
JobNo
FROM TimeTicketDet as tt
GROUP BY JobNo
) tt
ON tt.JobNo = o.JobNo
--***SUB QUERY (Receiver)
JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo
--***SUB QUERY (POProrate)***
JOIN
(
SELECT
j.JobNo,
SUM(j.TotalCost) as TotalCost
FROM
(
SELECT
por.JobNo,
CASE
WHEN pod.Unit = 'LOT' THEN SUM(pod.UnitCost*1)
ELSE SUM(por.Qty*pod.UnitCost)
END as TotalCost
FROM
PODet as pod
INNER JOIN
POReleases as por ON pod.PONum = por.PONum and pod.partno=por.partno
GROUP BY por.JobNo, pod.Unit
) j
GROUP BY j.JobNo
) POProrate
ON o.JobNo = POProrate.JobNo
--***SUB QUERY (WIPProrate)***
JOIN
(
SELECT
j.JobNo,
SUM(j.ProratedCost) as WIPProrateCost
FROM
(
SELECT
tt.StepNo,
tt.JobNo,
tt.ActualPayRate,
tt.BurdenRate,
tt.CycleTime,
tt.SetupTime,
tt.CycleTime + tt.SetupTime as TotalTime,
(tt.CycleTime + tt.SetupTime) * tt.ActualPayRate as LaborCost,
(tt.CycleTime + tt.SetupTime) * tt.BurdenRate as BurdenCost,
((tt.CycleTime + tt.SetupTime) * tt.ActualPayRate) + ((tt.CycleTime + tt.SetupTime) * tt.BurdenRate) as ProratedCost
FROM
TimeTicketDet as tt
) j
GROUP BY j.JobNo
) WIPProrate
ON WIPProrate.JobNo = o.JobNo
WHERE
o.Status = 'Open'
AND o.JobNo <> ''
AND ord.DateEnt <= #90daysago
AND po.DateEnt <= #90daysago
AND tt.MAXtt <= #90daysago
AND r.ReceiveDate <= #90daysago
)
SELECT *
FROM cte
WHERE
RowNum = 1

Your sub query needs to be a LEFT JOIN instead of a regular JOIN which will allow it to include results if present and NULL otherwise.
--***SUB QUERY (Receiver)
LEFT JOIN
(
SELECT
MAX(cast(r.ReceiveDate as DATE)) as ReceiveDate,
por.JobNo
FROM
POReleases as por
INNER JOIN
Receiver as r on por.PONum = r.PONum
GROUP BY por.JobNo
) r
ON r.JobNo = o.JobNo

Related

UPDATE all records from existing SELECT query

I have query to select data from related tables.
SELECT
s.id,
CASE
WHEN count(DISTINCT e.id) <> 0
THEN count(DISTINCT o.id) / count(DISTINCT e.id)
END OrdersAverageNumber
FROM
[School] s
JOIN
[SchoolStore] ss ON ss.SchoolId = s.Id
JOIN
[Event] e ON e.SchoolId = ss.SchoolId
AND e.IsDeleted = 0
AND e.Status = 1
AND e.Date >= #startDate
AND e.Date <= #endDate
JOIN
[Order] o ON o.EventId = e.id
AND o.OrderStatus = 1
AND o.CreatedDate >= #startDate
AND o.CreatedDate <= #endDate
GROUP BY
s.id;
But I can't understand what I need to change to update all OrdersAverageNumber records in School table with values from selection above.
You can use update:
with q as (< your query here >)
update s
set OrdersAverageNumber = q.OrdersAverageNumber
from school s join
q
on s.id = q.id;

SQL : Get Column table twice with differents clause where

I try to get the same column in the same table twice with different clauses :
My query:
SELECT
*
FROM
(SELECT TOP 10
CONVERT(DATE, attemptdate) AS Date,
Max(currentcount) AS A
FROM
logintracking
INNER JOIN
maxuser ON logintracking.loginid = maxuser.loginid
INNER JOIN
site ON site.siteid = maxuser.defsite
WHERE
attemptdate BETWEEN #dateDebut AND #dateFin
AND logintracking.clientaddr IN ('10.118.254.21', '10.118.254.156')
GROUP BY
CONVERT(DATE, attemptdate)
ORDER BY
CONVERT(DATE, attemptdate) ASC
) AS T1,
(SELECT TOP 10
CONVERT(DATE, attemptdate) AS Date,
MAX(currentcount) AS B
FROM
logintracking
INNER JOIN
maxuser ON logintracking.loginid = maxuser.loginid
INNER JOIN
site ON site.siteid = maxuser.defsite
WHERE
attemptdate BETWEEN #dateDebut AND #dateFin
AND logintracking.clientaddr = '10.118.254.35'
GROUP BY
CONVERT(DATE, attemptdate)
ORDER BY
CONVERT(DATE, attemptdate) ASC) AS T2
Result:
Desired result:
My objective is to get the same column 'max(currentcount)' twice and to apply different where clauses so to get two columns named (A & B), and i need also to show the date in the first column, can you please help ? Thanks
Since the only difference between A and B is logintracking.clientaddr, you can put that condition within a CASE statement within the MAX function:
SELECT CONVERT(DATE, attemptdate) AS Date,
MAX(CASE WHEN logintracking.clientaddr IN ( '10.118.254.21', '10.118.254.156' ) THEN currentcount END) AS A,
MAX(CASE WHEN logintracking.clientaddr IN ( '10.118.254.35' ) THEN currentcount END) AS B
FROM logintracking
INNER JOIN maxuser
ON logintracking.loginid = maxuser.loginid
INNER JOIN site
ON site.siteid = maxuser.defsite
WHERE attemptdate BETWEEN #dateDebut AND #dateFin
GROUP BY CONVERT(DATE, attemptdate)
ORDER BY CONVERT(DATE, attemptdate) ASC

SQL server show count 0 when no record is found

I'm trying to make this query show 0 in the "nb" field when there are no record found for a specific date. Right now the output is 0 row, unless the date i specify exists in the "Commande" table.
SELECT
isnull(COUNT(*), 0) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
f.Code_fournis
FROM Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '2015-10-28'
GROUP BY CONVERT(date, c.Date_commande), f.Code_fournis
ORDER BY c.date_commande desc
The problem is you can't count what isn't there. You need create a table allDates for all the dates. 100 years mean 36,500 rows so is a small table. Use this one as example
How can I generate a temporary table filled with dates in SQL Server 2000?
Then
SELECT
isnull(COUNT(*), 0) as nb,
CONVERT(date, AD.date) as Date_commande,
f.Code_fournis
FROM
allDates AD
LEFT JOIN Commande c
ON AD.date = CONVERT(date, c.Date_commande)
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '2015-10-28'
GROUP BY CONVERT(date, AD.date), f.Code_fournis
ORDER BY AD.date desc
Because '2015-10-28' does not exists in Commande, you need to create an row for it in a dummy table:
SELECT
SUM(case when c.Date_commande is null then 0 else 1 end) as nb,
d.Date_commande as Date_commande,
f.Code_fournis
FROM (values(cast('20150101' as date), 'XNZ') as d(Date_commande, Code_fournis)
LEFT JOIN Commande c on Cast(c.Date_commande as date) = d.Date_commande
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis and f.Code_fournis = d.Code_fournis
GROUP BY d.Date_commande, f.Code_fournis
ORDER BY d.Date_commande desc
This would work as well:
SELECT isnull(COUNT(*), 0) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
f.Code_fournis
From your query
Union All
Select 0, '20150101', 'XNZ'
Where not exist (
select 1
From Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis and = d.Code_fournis
Where f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '20150101'
)
Even though this is old and has a few downvotes, I recently solved my problem. I had to generate a table with dates.
SELECT SUM(CONVERT(int, case(vtl.oeil) WHEN RTRIM('I') THEN 2 ELSE 1 END)) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
RTRIM(f.Code_fournis) AS Code_fournis
FROM Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE c.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande)
BETWEEN '2015-11-30'
AND '2015-12-04'
GROUP BY CONVERT(date, c.Date_commande), f.Code_fournis
UNION ALL
SELECT '0', date, 'XNZ'
FROM allDates
WHERE date
BETWEEN '2015-11-30'
AND '2015-12-04'
AND date NOT IN (
SELECT convert(date, c.Date_commande) as date
FROM allDates ad
INNER JOIN Commande c
ON ad.date = convert(date, c.Date_commande)
WHERE c.Code_fournis = 'XNZ'
and convert(date, c.Date_commande)
BETWEEN '2015-11-30'
AND '2015-12-04'
)
ORDER BY c.date_commande asc
It's a bit different then what I asked for but hopefully it can help someone.

Only one expression can be specified in the select list when the subquery is introduced

I have this stored procedure...
SELECT
LTRIM(RTRIM([OF].OF_DISPLAYNAME)) AS [Officer_Name],
LTRIM(RTRIM([OF].OF_PIN)) AS Officer_Pin,
LTRIM(RTRIM([TO].TO_ACTIVITY)) AS Template_Site,
AC.AC_NAME AS Site_Name,
ZN.ZN_MANAGER AS Site_Manager,
AR.AR_DESCRIPTION AS Scheduler,
CONVERT(VARCHAR(10), #WeekCommencing, 6) AS [Week_Commencing],
CONVERT(VARCHAR(10), [OF].OF_DOL, 6) AS Leave_Date,
CAST((SELECT
(ISNULL(SUM(RO.RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)/60.0)
FROM
RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE
RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START BETWEEN #WeekCommencing AND #WeekEnding
AND RO.RO_STATUS IN ('COMP', 'CONF', 'TODO')
) AS DECIMAL(11,2)) AS HoursSum,
RSWH.dbo.RSWHF_GetMarker([OF].OF_PIN, #WeekCommencing, #WeekEnding) AS Marker,
CONVERT(VARCHAR(10), (SELECT MAX(RO.RO_SHIFT_START)
FROM RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START < GETDATE()
AND RO.RO_STATUS IN ('COMP', 'CONF', 'TODO')
), 6) AS Last_Worked_Shift,
CONVERT(VARCHAR(10), (SELECT TOP 1
HC.Effective_Date
FROM HR.dbo.HRST_Contract AS HC WITH(NOLOCK)
WHERE
HC.Of_Pin = [OF].OF_PIN
AND HC.SD_Contract = 1
ORDER BY
Effective_Date DESC
), 6) AS Contract_Sent_Date,
CONVERT(VARCHAR(10),
(
SELECT TOP 1
RO.RO_SHIFT_START
FROM
Rolecall.dbo.Roster AS RO WITH(NOLOCK)
WHERE
RO.RO_Activity = 'ENDASSIG'
AND RO.RO_STATUS <> 'CANC'
AND RO.RO_OFFICER =[OF].OF_PIN
AND RO.RO_SHIFT_START < #WeekEnding
ORDER BY
RO.RO_SHIFT_START DESC
), 6) AS Ass_End_Date,
ISNULL(CreatedBy, '') AS Checked_By,
---ISSUE IS OCCURRING HERE----
(
SELECT
SUM(a.[Value*NumofActivity]) + max(b.NumOfHoursWorkedInTheLast12Weeks) AS [TotalHoursWorkedInTheLast12Weeks],Markers
FROM
(
SELECT
RO_OFFICER [RO_OFFICER],RO_ACTIVITY , COUNT(RO_ACTIVITY)*Value as [Value*NumofActivity]
FROM
RoleCall.dbo.ROSTER as ro inner join [RSWH].DBO.[RSWHT_Hours_Assigned_To_Markers_LookUp] AS MR on RO_ACTIVITY = MR.MARKER
WHERE
ro_officer = [OF].OF_PIN
AND RO_STATUS = 'INFO'
AND RO_SHIFT_START between DATEADD(week, -12, GETDATE()) AND GETDATE()
GROUP BY
RO_OFFICER,RO_ACTIVITY,Value) a
JOIN
(
SELECT
RO_OFFICER [RO_OFFICER] ,(ISNULL(SUM(RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)/60.0)as [NumOfHoursWorkedInTheLast12Weeks],RSWH.dbo.RSWHF_GetMarker(RO_OFFICER, DATEADD(week, -12, GETDATE()), GETDATE()) AS Markers
FROM
ROLECALL.DBO.ROSTER as ro inner join [RSWH].DBO.[RSWHT_Hours_Assigned_To_Markers_LookUp] AS MR on RO_ACTIVITY = MR.MARKER
WHERE
RO_SHIFT_START >= DATEADD(week, -12, GETDATE()) AND RO_SHIFT_START <= GETDATE()
AND RO.RO_STATUS = 'INFO'
AND RO_OFFICER = [OF].OF_PIN
GROUP BY
RO_OFFICER
) b on a.RO_OFFICER = b.RO_OFFICER
GROUP BY A.RO_OFFICER,b.NumOfHoursWorkedInTheLast12Weeks,Markers)
FROM
RoleCall.dbo.OFFICER AS [OF] WITH (NOLOCK)
LEFT JOIN RoleCall.dbo.TEMPLATE AS [TO] WITH (NOLOCK) ON [TO].TO_PIN = [OF].OF_PIN AND [TO].TO_TYPE COLLATE Latin1_General_CS_AS = 'M'
LEFT JOIN RoleCall.dbo.ACTIVITY AS AC WITH (NOLOCK) ON AC.AC_PIN = [TO].TO_ACTIVITY
LEFT JOIN RoleCall.dbo.ZONE AS ZN WITH (NOLOCK) ON ZN.ZN_ZONE = AC.AC_ZONE
LEFT JOIN RoleCall.dbo.AREA AS AR WITH (NOLOCK) ON AR.AR_AREA = AC.AC_AREA
LEFT JOIN Appollo.ACMS.dbo.ACSMT_Checked_Officer AS CO WITH (NOLOCK) ON CO.OfficerPin = [OF].OF_PIN AND WeekCommencing BETWEEN #WeekCommencing AND #WeekEnding
WHERE
[OF].OF_PAYROLL_NO IN ('W', 'S')
AND [OF].OF_SKILLS = #Of_Skills --
AND (#Of_Skills = 'R' OR AC.AC_PARENT IN ('9947', '9133'))
AND ([OF].OF_DOL IS NULL OR [OF].OF_DOL > #WeekCommencing)
AND [OF].OF_RANK <> 'PT'
AND [OF].OF_RANK <> 'LW'
AND EXISTS (
SELECT
TOP 1 Of_Pin
FROM
HR.dbo.HRST_Contract AS HC WITH(NOLOCK)
WHERE
Of_Pin = [OF].OF_PIN
AND ISNULL(SD_Contract, 0) = 1
)
AND (
SELECT
ISNULL(SUM(RO.RO_SHIFT_LENGTH - RO_BREAK_LENGTH), 0.0)
FROM
RoleCall.dbo.ROSTER AS RO WITH(NOLOCK)
WHERE
RO.RO_OFFICER = [OF].OF_PIN
AND RO.RO_SHIFT_START BETWEEN #WeekCommencing AND #WeekEnding
AND (RO.RO_STATUS IN ('COMP', 'CONF', 'TODO') OR (RO_Activity ='LEAVE' AND RO_STATUS <> 'CANC'))
) < 420.0
AND (ISNULL(CreatedBy, '') = '' OR #UncheckedOfficersOnly = 0)
ORDER BY
Officer_Name,
Officer_Pin
The issue is I need to return the three columns which I'm trying to sum. I haven't got much experience in SQL and I was wondering if anyone has any suggestions or pointers for this to be done.
Thank you

Aggregate query returning multiple rows when I only want one

this is the original query
SELECT 'MSD-RES-CRUISE' AS QUERYNAME, dbo.BOOKINGS.USERID, SUM(dbo.BOOKINGS.APRICE) AS total, COUNT(dbo.BOOKINGS.USERID) AS TOTAL2
FROM dbo.BOOKINGS INNER JOIN dbo.TOURS ON dbo.BOOKINGS.TOUR = dbo.TOURS.TOUR INNER JOIN
dbo.MAJOR ON dbo.TOURS.MAJOR = dbo.MAJOR.MAJOR
WHERE (dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate))) AND (dbo.MAJOR.SDESCR = 'Cruises') AND
(dbo.BOOKINGS.USERID = #USER) AND (dbo.MAJOR.DIVISION = 'A') and dbo.BOOKINGS.STATUS <> 'XL' GROUP BY dbo.BOOKINGS.USERID
the query i want to join
SELECT calltimeint, avetimeint
FROM dbo.agentdailycalls
where userid = #user and date1 between #startdate and #enddate
where the userids match and the groupname matches query name
this is what i used
SELECT t0.QUERYNAME, t0.USERID, total, TOTAL2, calltimeint, avetimeint
FROM ( SELECT 'MSD-RES-CRUISE' AS QUERYNAME, dbo.BOOKINGS.USERID, SUM(dbo.BOOKINGS.APRICE) AS total, COUNT(dbo.BOOKINGS.USERID) AS TOTAL2
FROM dbo.BOOKINGS INNER JOIN dbo.TOURS ON dbo.BOOKINGS.TOUR = dbo.TOURS.TOUR INNER JOIN
dbo.MAJOR ON dbo.TOURS.MAJOR = dbo.MAJOR.MAJOR
WHERE (dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate))) AND (dbo.MAJOR.SDESCR = 'Cruises') AND
(dbo.BOOKINGS.USERID = #USER) AND (dbo.MAJOR.DIVISION = 'A') and dbo.BOOKINGS.STATUS <> 'XL' GROUP BY dbo.BOOKINGS.USERID
) t0
INNER JOIN ( SELECT sum(calltimeint) as calltimeint, sum(avetimeint) as avetimeint , userid
FROM dbo.agentdailycalls
where userid = #user and date1 between #startdate and #enddate and GroupName = 'MSD-RES-CRUISE'
group by userid
) t1 ON t1.userId = t0.USERID
Just do a JOIN on the two queries:
SELECT QUERYNAME, USERID, total, TOTAL2, calltimeint, avetimeint
FROM ('MSD-RES-CRUISE' ... GROUP BY abcfiles.dbo.BOOKINGS.USERID) t0
INNER JOIN (SELECT userid, groupname, calltimeint, avetimeint ... and #enddate) t1
ON t1.userId = t0.USERID AND t01.groupname = t0.QUERYNAME
OLD ANSWER, based on a previous version of the question
Instead of selecting calltimeint and avetimeint it looks like you want to select the SUM of each of those columns, and remove them from the GROUP BY:
SELECT ... SUM(dbo.agentdailycalls.calltimeint), SUM(dbo.agentdailycalls.avetimeint)
FROM dbo.BOOKINGS INNER JOIN ...
GROUP BY dbo.BOOKINGS.USERID
Adding them to the GROUP BY means you want a row for every different combination of these values. So, GROUP BY userid, calltimeint, avetimeint means "return one row for every different combination of userid, call time, and average time".
What you really meant (presumably) is "return one row for each user", so you should only have userid in the GROUP BY.
Try This:
SELECT 'MSD-RES-CRUISE' AS QUERYNAME
, abcfiles.dbo.BOOKINGS.USERID
, SUM(tt.calltime)
, SUM(tt.aveTimeint)
, SUM(abcfiles.dbo.BOOKINGS.APRICE) AS total
, COUNT(abcfiles.dbo.BOOKINGS.USERID) AS TOTAL2
FROM abcfiles.dbo.BOOKINGS
INNER JOIN abcfiles.dbo.TOURS
ON abcfiles.dbo.BOOKINGS.TOUR = abcfiles.dbo.TOURS.TOUR
INNER JOIN abcfiles.dbo.MAJOR
ON abcfiles.dbo.TOURS.MAJOR = abcfiles.dbo.MAJOR.MAJOR
INNER JOIN (SELECT
calltime
, aveTimeint
FROM
dbo.agentdailycalls adc
) tt
ON tt.userid = abcfiles.dbo.BOOKINDS.USERID
AND tt.date1 BETWEEN #startdate AND #endDate***
WHERE (abcfiles.dbo.BOOKINGS.BOOKED BETWEEN CONVERT(int, Dateadd(day,2, #startdate)) AND CONVERT(int, Dateadd(day,2, #enddate)))
AND (abcfiles.dbo.MAJOR.SDESCR = 'Cruises')
AND (abcfiles.dbo.BOOKINGS.USERID = #USER)
AND (abcfiles.dbo.MAJOR.DIVISION = 'A')
and abcfiles.dbo.BOOKINGS.STATUS <> 'XL'
GROUP BY abcfiles.dbo.BOOKINGS.USERID