Comparing Sum from 2 different Columns - sql

I'm trying to compare the sum of 2 different columns and I'm getting an error saying that I must declare #Base. Then I have tried to do something like #Base AS B, the error will disappear. But I'm not retrieving any data.
Can anyone help me with if I have made a typo or my INNER JOIN is wrong?
Declare #Base table(PickupDate smalldatetime, DeliveryDate smalldatetime, PickupAdrID int, PickupCustID varchar(10), DeliveryType char, DeliveryAdrID int, DeliveryCustID varchar(10), DeliveryAlias varchar (30), Volumen float, Weight float) Insert #Base(PickupDate,DeliveryDate, PickupAdrID, PickupCustID, DeliveryType, DeliveryAdrID, DeliveryCustID, DeliveryAlias, Volumen,Weight)
SELECT PickupDate,DeliveryDate, PickupAdrID, PickupCustID, DeliveryType, DeliveryAdrID, DeliveryCustID, DeliveryAlias, Volumen, Weight
FROM Sending
INNER JOIN Address_ViewI ON Sending.PickupAdrID = Address_ViewI.AdrID
INNER JOIN Address_ViewI AS Address_View_DE ON Sending.DeliveryAdrID = Address_View_DE.AdrID
WHERE (Address_ViewI.CountryUK = #puC AND Address_View_DE.CountryUK = #deC) AND (Sending.PickupDate >= #start) AND (Sending.PickupDate < #end) AND ((PickUpCustID Like 'TMHSE' OR DeliveryCustID like 'TMHSE' ) )
OR (Address_ViewI.CountryUK = #puC AND Address_View_DE.CountryUK = #deC) AND (Sending.PickupDate >= #start) AND (Sending.PickupDate < #end) AND ((PickUpCustID Like 'SomeName' OR DeliveryCustID like 'SomeName' ) )
SELECT totals.DeliveryAdrID, totals.PickupDate,
(CASE WHEN weightTOTAL <= volumenTOTAL THEN volumenTOTAL
WHEN weightTOTAL >= volumenTOTAL THEN weightTOTAL ELSE weightTOTAL END) AS InvoiceWeight
FROM #Base INNER JOIN
(SELECT DeliveryAdrID, CONVERT(CHAR(10),PickupDate,110) AS PickupDate,
CEILING(SUM(CASE Weight When 0 Then #zeroKiloVal ELSE Weight END)) AS WeightTOTAL,
CEILING(SUM(CASE Volumen WHEN 0 THEN (#zeroVoluVal * #zeroVoluFac) ELSE Volumen END)) AS volumenTOTAL,
COUNT(DeliveryAdrID)AS Packages
FROM #Base GROUP BY CONVERT(CHAR(10),PickupDate,110), DeliveryAdrID ) AS totals
ON #Base.DeliveryAdrID = totals.DeliveryAdrID AND CONVERT(CHAR(10),#Base.PickupDate,110) = totals.PickupDate
The full code is listed here http://pastie.org/8238866
And the error I'm getting

It worked for me when I placed an alias on the reference to #Base
Declare #zeroKiloVal float = 10
Declare #zeroVoluVal float = 10
Declare #zeroVoluFac float = 200
Declare #puC varchar = 'Sweden'
Declare #deC varchar = 'Sweden'
Declare #start smalldatetime = '2013-04-21'
Declare #end smalldatetime = '2013-05-01'
DECLARE #Base TABLE (SendingID INT, Barcode VARCHAR(50), PickupType CHAR, PickupDate SMALLDATETIME, DeliveryDate SMALLDATETIME, PickupAdrID INT, PickupCustID VARCHAR(10), DeliveryType CHAR, DeliveryAdrID INT, DeliveryCustID VARCHAR(10), DeliveryAlias VARCHAR (30), Volumen FLOAT, [Weight] FLOAT)
INSERT INTO #Base(SendingID, Barcode, PickupType, PickupDate,DeliveryDate, PickupAdrID, PickupCustID, DeliveryType, DeliveryAdrID, DeliveryCustID, DeliveryAlias, Volumen,[Weight])
SELECT SendingID = 1, Barcode= 1, PickupType= 1, PickupDate= 1,DeliveryDate= 1, PickupAdrID= 1, PickupCustID= 1, DeliveryType= 1, DeliveryAdrID= 1, DeliveryCustID= 1, DeliveryAlias= 1, Volumen= 1, [Weight] = 1
-- Replacing below code with stubbed data for testing.
-- SELECT SendingID, Barcode, PickupType, PickupDate,DeliveryDate, PickupAdrID, PickupCustID, DeliveryType, DeliveryAdrID, DeliveryCustID, DeliveryAlias, Volumen, Weight
-- FROM Sending
-- INNER JOIN Address_ViewI ON Sending.PickupAdrID = Address_ViewI.AdrID
-- INNER JOIN Address_ViewI AS Address_View_DE ON Sending.DeliveryAdrID = Address_View_DE.AdrID
-- WHERE (Address_ViewI.CountryUK = #puC AND Address_View_DE.CountryUK = #deC) AND (Sending.PickupDate >= #start) AND (Sending.PickupDate < #end) AND ((PickUpCustID Like 'TMHSE' OR DeliveryCustID like 'TMHSE' ) )
-- OR (Address_ViewI.CountryUK = #puC AND Address_View_DE.CountryUK = #deC) AND (Sending.PickupDate >= #start) AND (Sending.PickupDate < #end) AND ((PickUpCustID Like 'TMHSE' OR DeliveryCustID like 'TMHSE' ) )
SELECT totals.DeliveryAdrID
, totals.PickupDate
, InvoiceWeight =
(
CASE WHEN weightTOTAL <= volumenTOTAL THEN volumenTOTAL
WHEN weightTOTAL >= volumenTOTAL THEN weightTOTAL ELSE weightTOTAL END
)
FROM #Base AS B -- <<Added alias here>>
INNER JOIN
(
SELECT DeliveryAdrID
, PickupDate = CONVERT(CHAR(10),PickupDate,110)
, WeightTOTAL = CEILING(SUM(CASE [Weight] WHEN 0 THEN #zeroKiloVal ELSE [Weight] END))
, volumenTOTAL = CEILING(SUM(CASE Volumen WHEN 0 THEN (#zeroVoluVal * #zeroVoluFac) ELSE Volumen END))
, Packages = COUNT(DeliveryAdrID)
FROM #Base
GROUP BY CONVERT(CHAR(10),PickupDate,110), DeliveryAdrID
) AS totals ON B.DeliveryAdrID = totals.DeliveryAdrID
AND CONVERT(CHAR(10),B.PickupDate,110) = totals.PickupDate

Maybe you need to use some wildcards in the constants being compared with the Like operator, such as:
PickUpCustID Like '%TMHSE%' OR DeliveryCustID like '%TMHSE%'
Otherwise, I think you're just doing the same as
PickUpCustID = 'TMHSE' OR DeliveryCustID = 'TMHSE'
or
'TMHSE' in (PickUpCustID, DeliveryCustID)

I figured out the error it seems that my declared variables was missing something:
Declare #puC varchar = 'Sweden'
Declare #deC varchar = 'Sweden'
I changed it to
Declare #puC varchar (50) = 'Sweden'
Declare #deC varchar (50) = 'Sweden'
Thanks for your time guys

Related

Pagination over join table rows

I have a SQL server request with several tables, for example:
Workorder
WorkorderOccurrence
Schedule
A workorder occurrence is a realisation of a specific schedled workorder
For workorder 1 scheduled every day I have:
Workorder occurrence 1_1 the first day
Workorder occurrence 1_2 the second day
For a workorder 2 scheduled every week I have:
Workorder occurrence 1_7
Workorder occurrence 2_1
Workorder occurence 1_8
And so ...
I have a pagination on the front for an agenda view, but the pagination must be done on workorder and not on the occurrence.
Consequently I would like to return the workorder occurrences (maybe 50, 100, 200,).
but on the 20 workorder request by the pagination. But it seems to eeturn the 20 workorder occurrence with the offset and I don't know how to do this.
Below my attempt:
CREATE FUNCTION [dbo].[FctGetWorkorderAgenda]
(
#SeverityIDsFilter NVARCHAR(MAX) = '',
#Culture NVARCHAR(MAX) = 'FR-fr',
#StartDate DATETIMEOFFSET(7),
#EndDate DATETIMEOFFSET(7),
#PageNumber INT = 0,
#ResultByPage INT = 50
)
RETURNS #resTable TABLE
(
[WorkorderID] INT NOT NULL,
[EndDate] DATETIMEOFFSET(0),
[Name] NVARCHAR(MAX),
[FixedNextDate] DATETIMEOFFSET(0),
[NextDate] DATETIMEOFFSET(0),
[WorkorderStatutType] SMALLINT NOT NULL,
[FrequenceType] SMALLINT NOT NULL,
[DayOfWeek] INT,
[DayOfMonth] INT,
[MonthType] INT,
[DayOfMonthType] INT,
[FrequencyTime] TIME(7) NOT NULL,
[FrequencyOffset] INT,
[VendorName] NVARCHAR(MAX) NOT NULL,
[EquipmentName] NVARCHAR(MAX) NOT NULL,
[OrganizationID] INT NOT NULL,
[WorkorderSeverity] INT NOT NULL,
[FullCount] INT NOT NULL
)
AS
BEGIN
INSERT INTO #resTableBooking (
WO.WorkorderID,
WO.EndDate,
WO.Name,
WOO.FixedNextDate,
WOO.NextDate,
WOO.WorkorderStatutType,
S.FrequenceType,
S.DayOfWeek,
S.DayOfMonth,
S.MonthType,
S.DayOfMonthType,
[FrequencyTime],
S.FrequencyOffset,
[EquipmentName],
[WorkorderSeverity],
[FullCount])
SELECT
WorkorderID,
EndDate,
Name,
FixedNextDate,
NextDate,
WorkorderStatutType,
FrequenceType,
DayOfWeek,
DayOfMonth,
MonthType,
DayOfMonthType,
FrequencyTime,
FrequencyOffset,
EquipmentName,
WorkorderSeverity,
FullCount
FROM (
SELECT
WO.WorkorderID,
WO.EndDate,
WO.Name,
WOO.FixedNextDate,
WOO.NextDate,
WOO.WorkorderStatutType,
S.FrequenceType,
S.DayOfWeek,
S.DayOfMonth,
S.MonthType,
S.DayOfMonthType,
S.Time AS FrequencyTime,
S.FrequencyOffset,
E.Name AS EquipmentName,
(
CASE
WHEN (WO.EndDate IS NOT NULL AND (WO.EndDate <= WO.CreatedDate OR WO.NextDate >= WO.EndDate))
THEN -5 -- WorkorderSeverity.Closed
WHEN (WO.NextDate <= WO.CreatedDate)
THEN -4 -- WorkorderSeverity.DeadlineLate
WHEN (S.FrequenceType = 3) -- FrequencyType.EveryMonth
THEN IIF(
DATEADD(day, -7, WO.NextDate) <= WO.CreatedDate,
-3 /* WorkorderSeverity.DeadlineWarning */,
-2 /* WorkorderSeverity.InTime */
)
WHEN (S.FrequenceType = 1 OR S.FrequenceType = 6)
THEN IIF(
DATEADD(month, -1, WO.NextDate) <= WO.CreatedDate,
-3 /* WorkorderSeverity.DeadlineWarning */,
-2 /* WorkorderSeverity.InTime */
)
WHEN (S.FrequenceType = 0) -- FrequencyType.None
THEN CASE
WHEN (WO.NextDate <= WO.CreatedDate) THEN -4 /* WorkorderSeverity.DeadlineLate */
WHEN (DATEADD(day, -3, WO.NextDate) <= WO.CreatedDate) THEN -3
ELSE -2
END
ELSE -2
END
) AS WorkorderSeverity,
COUNT(WO.WorkorderID) OVER() FullCount
FROM [dbo].[WorkorderOccurrence] WOO WITH(NOLOCK)
JOIN [dbo].[Workorder] WO WITH(NOLOCK) ON WO.WorkorderID = WOO.WorkorderID
JOIN [dbo].[Schedule] S WITH(NOLOCK) ON S.ScheduleID = WO.WorkorderScheduleID
JOIN [dbo].[Equipment] E WITH(NOLOCK) ON E.EquipmentID = WO.EquipmentID
LEFT JOIN dbo.Localization l WITH(NOLOCK) ON l.CultureKey = E.CultureKey AND l.CultureName = #culture
WHERE (WOO.FixedNextDate IS NOT NULL AND WOO.FixedNextDate BETWEEN #StartDate AND #EndDate
OR WOO.NextDate IS NOT NULL AND WOO.NextDate BETWEEN #StartDate AND #EndDate)
GROUP BY WO.WorkorderID, WO.EndDate, WO.Name, WO.CreatedDate, WO.NextDate,
WOO.NextDate, WOO.FixedNextDate, WOO.WorkorderOccurrenceID, WOO.WorkorderStatutType,
S.FrequenceType, S.DayOfWeek, S.DayOfMonth, S.MonthType, S.DayOfMonthType, S.Time, S.FrequencyOffset,
E.Name
) AS base
LEFT JOIN
(
SELECT [value]
FROM STRING_SPLIT(#SeverityIDsFilter, ';')
) AS DynamicSeverityFilter ON WorkorderSeverity = DynamicSeverityFilter.[value]
WHERE ((DynamicSeverityFilter.[value] IS NULL AND #SeverityIDsFilter = '') OR DynamicSeverityFilter.[value] IS NOT NULL)
ORDER BY base.WorkorderID, base.NextDate
OFFSET (#PageNumber * #ResultByPage) ROWS
FETCH NEXT #ResultByPage ROWS ONLY
RETURN
END
I think the "easiest" is to make this a two-step solution.
Fetch head data first into a table variable and use the offset thingy.
Join the head data with the row data and select "out" it together.
Simplified version of your function (but i also think you should convert it to regular procedure)
CREATE FUNCTION [dbo].[FctGetWorkorderAgenda]
(
#SeverityIDsFilter NVARCHAR(MAX) = '',
#Culture NVARCHAR(MAX) = 'FR-fr',
#StartDate DATETIMEOFFSET(7),
#EndDate DATETIMEOFFSET(7),
#PageNumber INT = 0,
#ResultByPage INT = 50
)
RETURNS #resTable TABLE
(
[WorkorderID] INT NOT NULL,
...
)
AS
BEGIN
-- Get data by filter
declare #head TABLE (workorderID INT)
insert into #head (workOrderID)
select wo.workorderID
from Workorder wo
... needed joins
where <your filters>
ORDER BY ...
OFFSET (#PageNumber * #ResultByPage) ROWS
FETCH NEXT #ResultByPage ROWS ONLY
-- Return joined data to the client
insert into #resTableBooking (
WO.WorkorderID,
...
)
SELECT WorkorderID
, ...
FROM #head h
inner join rest...
...
ORDER BY ...
RETURN
END

Refresh issue with Stored Procedure in MSSQL

I have one SP for mobile application chat app (used with API) it has 25 filters and 10 tables join and return posts for user, it works good for 2 days but after 2 days it stop working, then i need to refresh it again with alter query or something then it start working for next few days.
If filter stop for any particular user than why others have issue with SP.
USE [DatabaseName]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROC [dbo].[uspGetShoutouts] (
#UserId UNIQUEIDENTIFIER,
#anotherUserid UNIQUEIDENTIFIER,
#Interest NVARCHAR(100),
#Gender NVARCHAR(100),
#AgeFrom INT,
#AgeTo INT,
#StartLatitude NUMERIC(20,15),
#StartLongitude NUMERIC(20,15),
#Radius FLOAT,
#Location BIT = NULL,
#IsTraveler BIT,
#IsLocal BIT,
#HomeTownCity VARCHAR(100),
#UserName NVARCHAR(200),
#FirstName NVARCHAR(200),
#LastName NVARCHAR(200),
#CreatedDate DATETIME,
#IsMyShoutout BIT,
#ShoutoutTypeId INT=0,
#PostTypeId INT=0,
#oldMoment BIT,
#SortExpression CHAR(1) = 1,
#CurrentPage INT = 1,
#PageSize INT = 10,
#IsFriend BIT=0,
#IsPrivate BIT,
#GroupId NVARCHAR(200),
#TotalRows INT OUTPUT
)
AS
BEGIN
DECLARE #UserList TABLE(
UserId uniqueidentifier,
FirstName NVARCHAR(100),
LastName NVARCHAR(100),
QuickBloxId NVARCHAR(100),
SocialId NVARCHAR(100),
Gender char(1),
Email NVARCHAR(100),
IsProfileImageSync bit,
IsFriend bit,
IsRequestSent bit,
RequestSender NVARCHAR(100),
IsBlocked bit,
FriendBlocked bit,
Age int,
HomeTownCity NVARCHAR(100),
ImageName NVARCHAR(200),
Distance numeric(20,6),
DistanceTemp numeric(20,6),
LastActiveDateTime datetime,
ShoutoutGuid uniqueidentifier,
ShoutoutId bigint not null,
InterestId int,
InterestName NVARCHAR(100),
ShoutoutImageName NVARCHAR(200),
Description NVARCHAR(max),
CreatedOn DateTime,
IsImageSync bit,
DisplayUpdatedOn NVARCHAR(50),
ShoutoutCity NVARCHAR(500),
ShoutoutCountry NVARCHAR(500),
AdministrativeAreaLevel1 NVARCHAR(500),
PlaceId NVARCHAR(500),
FormattedAaddress NVARCHAR(500),
Url NVARCHAR(500),
TotalLike int,
TotalComment int,
Selflike bit,
ShoutoutTypeId int,
ShoutoutType NVARCHAR(200),
PostTypeId int,
PostTypeName NVARCHAR(200),
oldMoment bit,
UserLatitude numeric(20,6),
UserLongitude numeric(20,6),
ShoutoutLatitude numeric(20,6),
ShoutoutLongitude numeric(20,6),
DistanceShoutoutMiles numeric(20,6)
)
SET NOCOUNT ON;
DECLARE #StartLatitude1 numeric(20,2) = #StartLatitude
DECLARE #StartLongitude1 numeric(20,2) =#StartLongitude;
;with
UserList as (
select
distinct
USRSHTOUT.ShoutoutId,
USRSHTOUT.ShoutoutGuid,
U.UserId,
U.FirstName,
U.LastName,
U.QuickbloxId,
convert(int,round(datediff(hour,dob,getdate())/8766.0,0)) as Age,
U.SocialId,
U.Gender,
U.Email,
isnull(U.IsProfileImageSync,0) IsProfileImageSync,
U.HomeTownCity,
U.ImageName,
isnull(fr.IsFriend,0) as IsFriend,
isnull(fr.IsRequestSent,0) as IsRequestSent,
isnull(fr.RequestSender,cast(cast(0 as binary) as uniqueidentifier)) as RequestSender,
isnull(fr.IsBlocked,0) as IsBlocked,
isnull(fr.FriendBlocked,0) as FriendBlocked,
[dbo].[fnCalcDistanceKM](cast(#StartLatitude1 as float),cast(#StartLongitude1 as float),cast (isnull(USRSHTOUT.Latitude,0) as float) ,cast(isnull(USRSHTOUT.Longitude,0) as float)) as Distance,
(geography::Point(coalesce(USRSHTOUT.Latitude,0), coalesce(USRSHTOUT.Longitude,0), 4326).STDistance(geography::Point(#StartLatitude1, #StartLongitude1, 4326))/1000) as DistanceTemp,
ULAL.UpdatedOn as LastActiveDateTime,
0 as InterestId,
'' as InterestName,
isnull(USRSHTOUT.ImageName,'') 'ShoutoutImageName',
isnull(USRSHTOUT.Description,'') Description,USRSHTOUT.CreatedOn,IsImageSync,
isnull(format(UGL.UpdatedOn,'dd-MMM, yyyy HH:mm tt'),'') 'DisplayUpdatedOn',
isnull(ADC.locality,'')[ShoutoutCity],
isnull(ADC.country,'')[ShoutoutCountry],
isnull(ADC.administrative_area_level_1,'') [AdministrativeAreaLevel1],
isnull(ADC.place_id,'') [PlaceId],
isnull(ADC.formatted_address,'') FormattedAaddress,
isnull(ADC.url,'') Url,
isnull(lt.TotalLike, 0) as TotalLike,
isnull(ct.TotalComment, 0) as TotalComment,
isnull(lt.SelfLike, 0) as SelfLike,
SHT.ShoutoutTypeId,
isnull(SHT.Name,'') ShoutoutType,
UPT.PostTypeId,
isnull(UPT.Name,'') PostTypeName,
USRSHTOUT.oldMoment,
UGL.Latitude 'UserLatitude',
UGL.Longitude 'UserLongitude',
USRSHTOUT.Latitude 'ShoutoutLatitude',
USRSHTOUT.Longitude 'ShoutoutLongitude',
DistanceShoutoutMiles
from
Users U
inner join UserShoutouts USRSHTOUT on U.UserId=USRSHTOUT.UserId
left join UserLastActivityLog ULAL on ULAL.UserId=U.UserId
left join UserGeoLocation UGL on UGL.UserId=U.UserId
left join AddressShoutoutMapping ASMP on ASMP.ShoutoutId=USRSHTOUT.ShoutoutId
left join AddressComponents ADC on ADC.AddressComponentId=ASMP.AddressComponentId
left join [ShoutoutType] SHT on SHT.ShoutoutTypeId=isnull(USRSHTOUT.ShoutoutTypeId,0)
LEFT JOIN [UserPostType] UPT ON UPT.PostTypeId = ISNULL(USRSHTOUT.PostTypeId,0)
cross apply (select cos(radians(#StartLatitude1)) * cos(radians(USRSHTOUT.Latitude)) * cos(radians(USRSHTOUT.Longitude) - radians(#StartLongitude1)) + sin(radians(#StartLatitude1)) * sin(radians(USRSHTOUT.Latitude))) T(ACosInput)
cross apply (select ((3959 * acos(case when abs(ACosInput) > 1 then sign(ACosInput)*1 else ACosInput end)))) T2(DistanceShoutoutMiles)
left join (
select ItemId,
count(1) TotalLike,
cast(sum(case when UserId = #anotherUserid then 1 else 0 end) as bit) as SelfLike
from dbo.LikeDetails
where Liked=1 and LikeSourceId=1
group by ItemId) as lt on USRSHTOUT.ShoutoutId = lt.ItemId
left join (
select ParentId,
count(1) as TotalComment
from Comments
where CommentSourceId=1 and Comments.IsDeleted=0
group by ParentId) as ct on USRSHTOUT.ShoutoutId = ct.ParentId
left join dbo.tvf_GetFriendsByUserId (#UserId) fr on u.UserId = fr.ThisFriendId
left join UserShoutoutsPrivate USP on USP.ShoutoutId = USRSHTOUT.ShoutoutId
left join UserInterest UI on UI.InterestId = USP.GroupId
left join Interest INTRST on INTRST.Id = UI.InterestId
where
USRSHTOUT.IsDeleted=0
and (((#oldMoment = 0) and USRSHTOUT.oldMoment = #oldMoment)
or ((#oldMoment = 1) and USRSHTOUT.oldMoment = 1 or USRSHTOUT.oldMoment = 0) )
and U.IsEmailVerified=1 and isnull(U.IsDeactivated,0)=0
and (#ShoutoutTypeId=0 or USRSHTOUT.ShoutoutTypeId=#ShoutoutTypeId)
and (#IsMyShoutout=0 or (#IsMyShoutout=1 and USRSHTOUT.UserId = #UserId))
and ((#UserName is not null and #UserName='all'
OR ((U.FirstName + ' ' + U.LastName) = #UserName)OR (U.FirstName like LTRIM(RTRIM(#UserName))+'%') OR (U.LastName like LTRIM(RTRIM(#UserName))+'%'))
OR ( #FirstName is not null AND #LastName is null and
((U.FirstName = #FirstName ) OR (U.FirstName like LTRIM(RTRIM(#FirstName))+'%')))
OR ( #LastName is not null AND #FirstName is null and
((U.LastName = #LastName ) OR (U.LastName like LTRIM(RTRIM(#LastName))+'%')))
OR ((( #FirstName is not null AND #LastName is not null AND
((U.FirstName + ' ' + U.LastName) = #FirstName + ' ' + #LastName) OR (U.FirstName like LTRIM(RTRIM(#FirstName))+'%')) and (U.LastName like LTRIM(RTRIM(#LastName))+'%'))))
and((#Interest <>'' AND #IsPrivate = 1 AND (exists (select * from dbo.UserInterest where (UserId = U.UserId and InterestId in (select * from dbo.Split(#Interest,','))))
or #Interest ='')
or(#IsPrivate = 1
and (UI.Interestid in (select items from dbo.Split(#GroupId,',')) and INTRST.IsPrivate = 1 and INTRST.IsDelete = 0 and USRSHTOUT.IsDeleted=0 and
USP.ShoutoutId = USRSHTOUT.ShoutoutId and UI.IsActive = 1 and USP.GroupId in (select items from dbo.Split(#GroupId,','))))
)
OR(#Interest <>'' AND #IsPrivate = 0 AND (exists (select * from dbo.UserInterest where (UserId = U.UserId and InterestId in (select * from dbo.Split(#Interest,','))))
or #Interest ='')
or(#IsPrivate = 1
and (UI.Interestid in (select items from dbo.Split(#GroupId,',')) and INTRST.IsPrivate = 1 and INTRST.IsDelete = 0 and USRSHTOUT.IsDeleted=0 and
USP.ShoutoutId = USRSHTOUT.ShoutoutId and UI.IsActive = 1 and USP.GroupId in (select items from dbo.Split(#GroupId,','))))
)
OR(#Interest ='' AND #IsPrivate = 0 AND (exists (select * from dbo.UserInterest where (UserId = U.UserId and InterestId in (select * from dbo.Split(#Interest,','))))
or #Interest =''))
)
and (#PostTypeId=0 or USRSHTOUT.PostTypeId=#PostTypeId)
)
insert into #UserList
select
UserId,
FirstName,
LastName,
QuickBloxId,
SocialId,
Gender,
Email,
IsProfileImageSync,
IsFriend,
IsRequestSent,
RequestSender,
IsBlocked,
FriendBlocked,
Age,
HomeTownCity,
ImageName,
Distance,
DistanceTemp,
LastActiveDateTime,
ShoutoutGuid,
ShoutoutId,
InterestId,
InterestName,
ShoutoutImageName,
Description,
CreatedOn,
IsImageSync,
DisplayUpdatedOn,
ShoutoutCity,
ShoutoutCountry,
AdministrativeAreaLevel1,
PlaceId,
FormattedAaddress,
Url,
u.TotalLike,
u.TotalComment,
u.Selflike,
ShoutoutTypeId,
ShoutoutType,
PostTypeId,
PostTypeName,
oldMoment,
UserLatitude,
UserLongitude,
ShoutoutLatitude,
ShoutoutLongitude,
DistanceShoutoutMiles
from UserList u
where
(#Gender ='' or ((Gender in(select * from dbo.Split(#Gender,','))) or (#Gender like '%3%' and Gender=0)))
and(
((#AgeFrom = 18) AND ((#AgeTo= 65 and Age >= 15 )
or (Age >= 15 and Age <= #AgeTo)))
OR
((#AgeTo= 65 and Age >= #AgeFrom )
or (Age >= #AgeFrom and Age <= #AgeTo))
)
and IsBlocked <> 1
and FriendBlocked <> 1
and (#Location=0 or ((DistanceShoutoutMiles<= #Radius) or (#IsLocal=1 and HomeTownCity=#HomeTownCity)))
and (#IsFriend=0 or (#IsFriend=1 and IsFriend=1))
and (#Location=0 or (
((#IsTraveler=1 and #IsLocal=1) or (#IsTraveler=0 and #IsLocal=0)) or
((#IsTraveler=1 and #IsLocal=0 and lower(HomeTownCity) != lower(#HomeTownCity))
or (#IsTraveler=0 and #IsLocal=1 and lower(HomeTownCity) = lower(#HomeTownCity)))))OPTION(RECOMPILE)
set #TotalRows = ##rowcount
IF(#CurrentPage=0)
begin
select * from #UserList order by Distance asc OPTION(OPTIMIZE FOR UNKNOWN)
end
ELSE
BEGIN
declare #OffSetSize as bigint
set #OffSetSize = ((#CurrentPage * #PageSize) - #PageSize)
IF (#SortExpression = '1')
BEGIN
SELECT *
FROM #UserList
WHERE CreatedOn<#CreatedDate
ORDER BY CreatedOn DESC
OFFSET #OffSetSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(OPTIMIZE FOR UNKNOWN)
END
ELSE IF (#SortExpression = '2')
BEGIN
SELECT *
FROM #UserList
WHERE CreatedOn>#CreatedDate
ORDER BY CreatedOn DESC
OFFSET #OffSetSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(OPTIMIZE FOR UNKNOWN)
END
ELSE IF (#SortExpression = '3')
BEGIN
SELECT *
FROM #UserList
ORDER BY Distance ASC, CreatedOn DESC
OFFSET #OffSetSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(OPTIMIZE FOR UNKNOWN)
END
ELSE IF (#SortExpression = '4')
BEGIN
SELECT *
FROM #UserList
ORDER BY Distance ASC
OFFSET #OffSetSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(OPTIMIZE FOR UNKNOWN)
END
ELSE
BEGIN
SELECT *
FROM #UserList
ORDER BY CreatedOn DESC
OFFSET #OffSetSize ROWS
FETCH NEXT #PageSize ROWS ONLY
OPTION(OPTIMIZE FOR UNKNOWN)
END
END
ENDGO

MOST RECENT VALUE (CAN ANYONE DO THIS)

ive been told by my collegue to do this
"Perhaps what you can do is run a second table between #Basic and #Product where you only update the new retail column with the top 1 based on valid from desc for each currency code from #Basic?"
Create Table #Basic(
ProductCode Int,
ContractNo Int,
ProductDescription Varchar (max),
CGNo Nvarchar(MAX),
SCGNo Nvarchar(MAX),
EmpNo Int,
CurrencyCode NVARCHAR(MAX),
Retail decimal (38, 2),
ValidFrom datetime,
Active int,
ValidForCountry int
)
Insert Into #Basic
SELECT
c.ProductCode
,ContractNo
,p.Description
,p.CGNo
,p.SCGNo
,p.EmpNo
,r.CurrencyCode
,r.Retail
,r.ValidFrom
,p.active
,c.Validforcountry
FROM CONTRACT c
LEFT JOIN
(SELECT Distinct
ProductCode,
CurrencyCode,
Retail,
ValidFrom
From DIVRETAIL) as r on c.ProductCode = r.ProductCode
LEFT JOIN product p on c.ProductCode = p.ProductCode
WHERE ContractNo = 144546
And r.ValidFrom <= #enddate
SELECT Distinct
ProductCode,
CurrencyCode,
Retail,
ValidFrom
From DIVRETAIL
update #Basic
set Retail =(
select top 1 retail From DIVRETAIL
create table #basicretail
(ProductCode int
,ContractNo int
,Description varchar(MAX)
,CGNo int
,SCGNo int
,EmpNo int
,CurrencyCode varchar(10)
,Retail int
,ValidFrom datetime
,active int
,Validforcountry int
)
CREATE TABLE #Product
(
ProductCode Int,
ContractNo Int,
ProductDescription Varchar (max),
CGNo Nvarchar(MAX),
SCGNo Nvarchar(MAX),
EmpNo Int,
CurrencyCode NVARCHAR(MAX),
Retail decimal (38, 2),
ValidFrom datetime,
Active int,
ValidForCountry int,
Cost decimal (38,3)
)
INSERT INTO #Product
SELECT
ProductCode
,ContractNo
,ProductDescription
,CGNo
,SCGNo
,EmpNo
,CurrencyCode
,Retail
,ValidFrom
,Active
,ValidForCountry
,NULL
FROM #basic
UPDATE #Product
SET #Product.Cost =
(CASE WHEN #Product.CurrencyCode = 'EUR' THEN
(SELECT TOP 1
Case when c.IncoTermtype IN (1,9) then b.DDP/p.Packsize
when c.IncoTermtype IN (2,12) then b.DAT/p.Packsize
when c.IncoTermtype = 10 then (b.FOB+b.Freight)/p.Packsize
when c.IncoTermtype = 13 then (b.ExWorks+Freight)/p.Packsize else 0 End as Casecost
FROM braketvalue b
LEFT JOIN CONTRACT c on b.ContractNo = c.ContractNo
LEFT JOIN PRODUCT p on c.ProductCode = p.ProductCode
WHERE ValidFrom <= #enddate
AND b.DivNo like '8__'
AND #Product.CurrencyCode = 'EUR'
AND #Product.ContractNo = b.ContractNo)
ELSE
(SELECT TOP 1
Case when c.IncoTermtype IN (1,9) then b.DDP/p.Packsize
when c.IncoTermtype IN (2,12) then b.DAT/p.Packsize
when c.IncoTermtype = 10 then (b.FOB+b.Freight)/p.Packsize
when c.IncoTermtype = 13 then (b.ExWorks+Freight)/p.Packsize else 0 End as Casecost
FROM braketvalue b
LEFT JOIN CONTRACT c on b.ContractNo = c.ContractNo
LEFT JOIN PRODUCT p on c.ProductCode = p.ProductCode
WHERE ValidFrom <= #enddate
AND b.DivNo like '7__'
AND #Product.CurrencyCode = '£'
AND #Product.ContractNo = b.ContractNo)
END
)
I think you meant to say >= instead like
WHERE
r.ValidFrom >= '2015-01-07'
As well, move the conditions from WHERE clause to JOIN ON clause
From DIVTAIL) as r on c.ProductCode = r.ProductCode
AND r.ValidFrom >= '2015-01-07'
LEFT JOIN product p on c.ProductCode = p.ProductCode
AND p.CGNo = '01' AND p.SCGNo = '01' AND p.ProductCode = 3317
If you don't want an exact date you might have to do something like a date range that is calculated based on the date passed in. So your JOIN would be like LEFT JOIN ON date between BeginningDate and EndDate

SQL Query Execution using parameter

I am having problems figuring out why a query is taking drastically longer to run based on me swapping out a parameter against a real value.
DECLARE #quarter int
DECLARE #year int
DECLARE #countOfUnitsBought int
set #year = 2009
set #quarter = 1
set #countOfUnitsBought = 4;
with res
as
(
select
o.account_id
--,orderyear
--,orderquarter
from
fmtables.[dbo].[orders] o
--cross apply(values(year(o.[ship_date]))) as a1(orderyear)
--cross apply(values(DatePart(quarter,(o.[ship_date])))) as a2(orderquarter)
where
ship_date = (select min(ship_date) from fmtables.[dbo].[orders] mo where [account_id] = o.account_id) and
total_value > 0 AND
order_status NOT LIKE 'return%' AND
order_status NOT LIKE 'cancel%' AND
order_status NOT LIKE 'freeze%' and
CAST(DatePart(quarter,(o.[ship_date])) as int) = #quarter and
year(o.[ship_date]) = #year and
(select sum(quantity) from fmtables..[orders] ox inner join fmtables..[orderlines] olx on ox.order_id = olx.order_id
where olx.order_id = o.order_id and [product_code] in(select [product_code] from fmtables..[products] where [category_code] in('1','2','3','4'))) >= #countOfUnitsBought
)
select * from res;
This query takes 43 seconds to run.
Now if I simply replace the #quarter and change to a literal
CAST(DatePart(quarter,(o.[ship_date])) as int) = 1 and
it now takes 1 second.
Can anyone please give me a clue as to why and if I need to change some casting to help.
Thanks
Scott
EDIT:
So I manage to get it whizzing through with the help of everyone's comments.
I used a mix of passing the parameters from the inputs and then through to a 'local' variable inside the procedure.
alter procedure [dbo].[Lifetime_HeadsetUnits]
#inquarter int , #inyear int, #incountOfUnitsBought int
as
DECLARE #quarter int
DECLARE #year int
declare #countOfUnitsBought int
select #quarter = #inquarter
select #year = #inyear
select #countOfUnitsBought = #incountOfUnitsBought
and also the
OPTION (OPTIMIZE FOR(#quarter = 1))
as part of the final output query.
Try this instead. I rewrote the datepart so indexes can be, used and the database is not making the long calculation on all rows. In other words I made your datecalculation sargable:
DECLARE #quarter int
DECLARE #year int
DECLARE #countOfUnitsBought int
set #year = 2009
set #quarter = 1
declare #from datetime = dateadd(quarter, #quarter - 1, cast(#year as char(4)))
set #countOfUnitsBought = 4;
with res
as
(
select
o.account_id
from
fmtables.[dbo].[orders] o
where
ship_date =
(select min(ship_date)
from fmtables.[dbo].[orders] mo
where [account_id] = o.account_id) and
total_value > 0 AND
order_status NOT LIKE 'return%' AND
order_status NOT LIKE 'cancel%' AND
order_status NOT LIKE 'freeze%' and
o.[ship_date] >= #quarter and
o.[ship_date] < DATEADD(QUARTER, 1, #from) and
(select sum(quantity) from fmtables..[orders] ox
inner join fmtables..[orderlines] olx on ox.order_id = olx.order_id
where [product_code] in(select [product_code] from fmtables..[products]
where [category_code] in('1','2','3','4'))) >= #countOfUnitsBought
)
select * from res;
Are you running an sql-server 2008 ? There is a bug that could also explain your performance issues.

Rewriting SQL query to simplify logic

I'm quite a newbie in optimizing queries.. it would be a first for me to handle other persons query and optimize it to improve performance. Can you kindly give me advice on which part of the query could I simplify in order to improve its performance....
CREATE FUNCTION SALES
(#SUPPLIERCODE VARCHAR(15),
#BATCHID VARCHAR(50))
RETURNS
#STOCKDETAILS TABLE([ID] CHAR(1),
[BATCH RECEIVEDATE] DATETIME,
SUPPLIERCODE VARCHAR(15),
[NOW - RECEVEDATE] INT,
[DUEDATE] VARCHAR(50)
)
AS
BEGIN
DECLARE #RECEIVEDATE DATETIME,
#SUPPLIERCODE1 VARCHAR(15)
SELECT TOP 1
#RECEIVEDATE = O.ReceivedDate,
#SUPPLIERCODE1 = A.SUPPLIERCODE
FROM
TRANSACT.dbo.FIELDS A WITH(NOLOCK)
INNER JOIN
TRANSACT.dbo.DELIV O WITH(NOLOCK) ON O.BATCHID = A.BATCHID
DECLARE #ID1 TABLE(SUPPLIERCODE VARCHAR(50))
INSERT INTO #ID1
SELECT P.SUPPLIERCODE
FROM
(SELECT
[SUPPLIERCODE] = SUPPLIERCODE,
[TOTAL] = ISNULL(SUM(ITEMPRICE + (ITEMPRICE * .12)), 0)
FROM TRANSACT.dbo.ProviderDiscount WITH(NOLOCK)
WHERE ACQUIREDDATE <> '1900-01-01 00:00:00.000'
AND SUPPLIERCODE = #SUPPLIERCODE1
GROUP BY SUPPLIERCODE) P
WHERE P.TOTAL <> 0
DECLARE #ID TABLE ([BATCH RECEIVEDATE] DATETIME,
SUPPLIERCODE VARCHAR(15),
ACQUIREDDATE DATETIME,
Coverage VARCHAR(20),
CoverageItem VARCHAR(10),
[NOW - RECEVEDATE] INT,
DiscTerm1 INT, DiscTerm2 INT,
DiscTerm3 INT, DiscTerm4 INT,
DiscTerm5 INT,
[NEW ACQUIREDDATE] VARCHAR(50)
)
INSERT INTO #ID
SELECT DISTINCT
[BATCH RECEIVEDATE] = #RECEIVEDATE,
B.SUPPLIERCODE,
B.ACQUIREDDATE,
B.Coverage,
B.CoverageItem,
[NOW - RECEVEDATE] = DATEDIFF(DAY,#RECEIVEDATE,GETDATE()),
B.DiscTerm1, B.DiscTerm2, B.DiscTerm3,
B.DiscTerm4, B.DiscTerm5,
[NEW ACQUIREDDATE] = TRANSACT.dbo.fxnGetIDNewACQUIREDDATE(B.DiscTerm1, B.DiscTerm2, B.DiscTerm3, B.DiscTerm4, B.DiscTerm5, #RECEIVEDATE)
FROM
TRANSACT.dbo.ProviderDiscount B WITH(NOLOCK)
INNER JOIN
(SELECT
[ACQUIREDDATE] = MAX(ACQUIREDDATE),
[REOD] = MAX(REOD)
FROM
TRANSACT.dbo.ProviderDiscount B2 WITH(NOLOCK)
INNER JOIN
#ID1 B1 ON B1.SUPPLIERCODE = B2.SUPPLIERCODE
WHERE
B2.Coverage = #CLAIMTYPE
AND B2.ACQUIREDDATE < #RECEIVEDATE) B3 ON B3.REOD = B.REOD
INSERT INTO #STOCKDETAILS
SELECT DISTINCT
[ID] = 'Y',
[BATCH RECEIVEDATE],
SUPPLIERCODE,
[NOW - RECEVEDATE],
[DUEDATE] = MIN([NEW ACQUIREDDATE])
FROM
#ID
WHERE
ISNULL([NEW ACQUIREDDATE],'NONE') <> 'NONE'
GROUP BY
[BATCH RECEIVEDATE], SUPPLIERCODE, [NOW - RECEVEDATE]
RETURN
END
Well, here's one thing you can do.
DECLARE #ID1 TABLE(SUPPLIERCODE VARCHAR(50))
INSERT INTO #ID1
SELECT P.SUPPLIERCODE
FROM
(
SELECT
[SUPPLIERCODE] = SUPPLIERCODE,
[TOTAL] = ISNULL(SUM(ITEMPRICE+(ITEMPRICE*.12)),0)
FROM TRANSACT.dbo.ProviderDiscount WITH(NOLOCK)
WHERE ACQUIREDDATE <> '1900-01-01 00:00:00.000'
AND SUPPLIERCODE = #SUPPLIERCODE1
GROUP BY SUPPLIERCODE
) P
WHERE P.TOTAL <> 0
Can be rewritten stripped of lots of extra. Maybe even more than I do here:
DECLARE #ID1 TABLE(SUPPLIERCODE VARCHAR(50))
INSERT INTO #ID1
SELECT SUPPLIERCODE
FROM TRANSACT.dbo.ProviderDiscount WITH(NOLOCK)
WHERE ACQUIREDDATE <> '1900-01-01 00:00:00.000'
AND SUPPLIERCODE = #SUPPLIERCODE1
GROUP BY SUPPLIERCODE
HAVING ISNULL(SUM(ITEMPRICE),0) <> 0
This almost looks like test question for refactoring SQL.