TSQL Conditionally Select Specific Value - sql

This is a follow-up to #1644748 where I successfully answered my own question, but Quassnoi helped me to realize that it was the wrong question. He gave me a solution that worked for my sample data, but I couldn't plug it back into the parent stored procedure because I fail at SQL 2005 syntax. So here is an attempt to paint the broader picture and ask what I actually need.
This is part of a stored procedure that returns a list of items in a bug tracking application I've inherited. There are are over 100 fields and 26 joins so I'm pulling out only the mostly relevant bits.
SELECT
tickets.ticketid,
tickets.tickettype,
tickets_tickettype_lu.tickettypedesc,
tickets.stage,
tickets.position,
tickets.sponsor,
tickets.dev,
tickets.qa,
DATEDIFF(DAY, ticket_history_assignment.savedate, GETDATE()) as 'daysinqueue'
FROM
dbo.tickets WITH (NOLOCK)
LEFT OUTER JOIN dbo.tickets_tickettype_lu WITH (NOLOCK) ON tickets.tickettype = tickets_tickettype_lu.tickettypeid
LEFT OUTER JOIN dbo.tickets_history_assignment WITH (NOLOCK) ON tickets_history_assignment.ticketid = tickets.ticketid
AND tickets_history_assignment.historyid = (
SELECT
MAX(historyid)
FROM
dbo.tickets_history_assignment WITH (NOLOCK)
WHERE
tickets_history_assignment.ticketid = tickets.ticketid
GROUP BY
tickets_history_assignment.ticketid
)
WHERE
tickets.sponsor = #sponsor
The area of interest is the daysinqueue subquery mess. The tickets_history_assignment table looks roughly as follows
declare #tickets_history_assignment table (
historyid int,
ticketid int,
sponsor int,
dev int,
qa int,
savedate datetime
)
insert into #tickets_history_assignment values (1521402, 92774,20,14, 20, '2009-10-27 09:17:59.527')
insert into #tickets_history_assignment values (1521399, 92774,20,14, 42, '2009-08-31 12:07:52.917')
insert into #tickets_history_assignment values (1521311, 92774,100,14, 42, '2008-12-08 16:15:49.887')
insert into #tickets_history_assignment values (1521336, 92774,100,14, 42, '2009-01-16 14:27:43.577')
Whenever a ticket is saved, the current values for sponsor, dev and qa are stored in the tickets_history_assignment table with the ticketid and a timestamp. So it is possible for someone to change the value for qa, but leave sponsor alone.
What I want to know, based on all of these conditions, is the historyid of the record in the tickets_history_assignment table where the sponsor value was last changed so that I can calculate the value for daysinqueue. If a record is inserted into the history table, and only the qa value has changed, I don't want that record. So simply relying on MAX(historyid) won't work for me.
Quassnoi came up with the following which seemed to work with my sample data, but I can't plug it into the larger query, SQL Manager bitches about the WITH statement.
;WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ticketid ORDER BY savedate DESC) AS rn
FROM #Table
)
SELECT rl.sponsor, ro.savedate
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.savedate
FROM rows rc
JOIN rows rn
ON rn.ticketid = rc.ticketid
AND rn.rn = rc.rn + 1
AND rn.sponsor <> rc.sponsor
WHERE rc.ticketid = rl.ticketid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
I played with it yesterday afternoon and got nowhere because I don't fundamentally understand what is going on here and how it should fit into the larger context.
So, any takers?
UPDATE
Ok, here's the whole thing. I've been switching some of the table and column names in an attempt to simplify things so here's the full unedited mess.
snip - old bad code
Here are the errors:
Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 159
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Procedure usp_GetProjectRecordsByAssignment, Line 179
Incorrect syntax near ')'.
Line numbers are of course not correct but refer to
;WITH rows AS
And the ')' char after the WHERE rl.rn = 1
)
Respectively
Is there a tag for extra super long question?
UPDATE #2
Here is the finished query for anyone who may need this:
CREATE PROCEDURE [dbo].[usp_GetProjectRecordsByAssignment]
(
#assigned numeric(18,0),
#assignedtype numeric(18,0)
)
AS
SET NOCOUNT ON
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY recordid ORDER BY savedate DESC) AS rn
FROM projects_history_assignment
)
SELECT projects_records.recordid,
projects_records.recordtype,
projects_recordtype_lu.recordtypedesc,
projects_records.stage,
projects_stage_lu.stagedesc,
projects_records.position,
projects_position_lu.positiondesc,
CASE projects_records.clientrequested
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS clientrequested,
projects_records.reportingmethod,
projects_reportingmethod_lu.reportingmethoddesc,
projects_records.clientaccess,
projects_clientaccess_lu.clientaccessdesc,
projects_records.clientnumber,
projects_records.project,
projects_lu.projectdesc,
projects_records.version,
projects_version_lu.versiondesc,
projects_records.projectedversion,
projects_version_lu_projected.versiondesc AS projectedversiondesc,
projects_records.sitetype,
projects_sitetype_lu.sitetypedesc,
projects_records.title,
projects_records.module,
projects_module_lu.moduledesc,
projects_records.component,
projects_component_lu.componentdesc,
projects_records.loginusername,
projects_records.loginpassword,
projects_records.assistedusername,
projects_records.browsername,
projects_browsername_lu.browsernamedesc,
projects_records.browserversion,
projects_records.osname,
projects_osname_lu.osnamedesc,
projects_records.osversion,
projects_records.errortype,
projects_errortype_lu.errortypedesc,
projects_records.gsipriority,
projects_gsipriority_lu.gsiprioritydesc,
projects_records.clientpriority,
projects_clientpriority_lu.clientprioritydesc,
projects_records.scheduledstartdate,
projects_records.scheduledcompletiondate,
projects_records.projectedhours,
projects_records.actualstartdate,
projects_records.actualcompletiondate,
projects_records.actualhours,
CASE projects_records.billclient
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS billclient,
projects_records.billamount,
projects_records.status,
projects_status_lu.statusdesc,
CASE CAST(projects_records.assigned AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
WHEN '20000' THEN 'Client'
WHEN '30000' THEN 'Tech Support'
WHEN '40000' THEN 'LMI Tech Support'
WHEN '50000' THEN 'Upload'
WHEN '60000' THEN 'Spider'
WHEN '70000' THEN 'DB Admin'
ELSE rtrim(users_assigned.nickname) + ' ' + rtrim(users_assigned.lastname)
END AS assigned,
CASE CAST(projects_records.assigneddev AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assigneddev.nickname) + ' ' + rtrim(users_assigneddev.lastname)
END AS assigneddev,
CASE CAST(projects_records.assignedqa AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assignedqa.nickname) + ' ' + rtrim(users_assignedqa.lastname)
END AS assignedqa,
CASE CAST(projects_records.assignedsponsor AS VARCHAR(5))
WHEN '0' THEN 'N/A'
WHEN '10000' THEN 'Unassigned'
ELSE rtrim(users_assignedsponsor.nickname) + ' ' + rtrim(users_assignedsponsor.lastname)
END AS assignedsponsor,
projects_records.clientcreated,
CASE projects_records.clientcreated
WHEN '1' THEN 'Yes'
WHEN '0' THEN 'No'
END AS clientcreateddesc,
CASE projects_records.clientcreated
WHEN '1' THEN rtrim(clientusers_createuser.firstname) + ' ' + rtrim(clientusers_createuser.lastname) + ' (Client)'
ELSE rtrim(users_createuser.nickname) + ' ' + rtrim(users_createuser.lastname)
END AS createuser,
projects_records.createdate,
projects_records.savedate,
projects_resolution.sitesaffected,
projects_sitesaffected_lu.sitesaffecteddesc,
DATEDIFF(DAY, projects_history_assignment.savedate, GETDATE()) as 'daysinqueue',
projects_records.iOnHitList,
projects_records.changetype
FROM
dbo.projects_records WITH (NOLOCK)
LEFT OUTER JOIN dbo.projects_recordtype_lu WITH (NOLOCK) ON projects_records.recordtype = projects_recordtype_lu.recordtypeid
LEFT OUTER JOIN dbo.projects_stage_lu WITH (NOLOCK) ON projects_records.stage = projects_stage_lu.stageid
LEFT OUTER JOIN dbo.projects_position_lu WITH (NOLOCK) ON projects_records.position = projects_position_lu.positionid
LEFT OUTER JOIN dbo.projects_reportingmethod_lu WITH (NOLOCK) ON projects_records.reportingmethod = projects_reportingmethod_lu.reportingmethodid
LEFT OUTER JOIN dbo.projects_lu WITH (NOLOCK) ON projects_records.project = projects_lu.projectid
LEFT OUTER JOIN dbo.projects_version_lu WITH (NOLOCK) ON projects_records.version = projects_version_lu.versionid
LEFT OUTER JOIN dbo.projects_version_lu projects_version_lu_projected WITH (NOLOCK) ON projects_records.projectedversion = projects_version_lu_projected.versionid
LEFT OUTER JOIN dbo.projects_sitetype_lu WITH (NOLOCK) ON projects_records.sitetype = projects_sitetype_lu.sitetypeid
LEFT OUTER JOIN dbo.projects_module_lu WITH (NOLOCK) ON projects_records.module = projects_module_lu.moduleid
LEFT OUTER JOIN dbo.projects_component_lu WITH (NOLOCK) ON projects_records.component = projects_component_lu.componentid
LEFT OUTER JOIN dbo.projects_browsername_lu WITH (NOLOCK) ON projects_records.browsername = projects_browsername_lu.browsernameid
LEFT OUTER JOIN dbo.projects_osname_lu WITH (NOLOCK) ON projects_records.osname = projects_osname_lu.osnameid
LEFT OUTER JOIN dbo.projects_errortype_lu WITH (NOLOCK) ON projects_records.errortype = projects_errortype_lu.errortypeid
LEFT OUTER JOIN dbo.projects_resolution WITH (NOLOCK) ON projects_records.recordid = projects_resolution.recordid
LEFT OUTER JOIN dbo.projects_sitesaffected_lu WITH (NOLOCK) ON projects_resolution.sitesaffected = projects_sitesaffected_lu.sitesaffectedid
LEFT OUTER JOIN dbo.projects_gsipriority_lu WITH (NOLOCK) ON projects_records.gsipriority = projects_gsipriority_lu.gsipriorityid
LEFT OUTER JOIN dbo.projects_clientpriority_lu WITH (NOLOCK) ON projects_records.clientpriority = projects_clientpriority_lu.clientpriorityid
LEFT OUTER JOIN dbo.projects_status_lu WITH (NOLOCK) ON projects_records.status = projects_status_lu.statusid
LEFT OUTER JOIN dbo.projects_clientaccess_lu WITH (NOLOCK) ON projects_records.clientaccess = projects_clientaccess_lu.clientaccessid
LEFT OUTER JOIN dbo.users users_assigned WITH (NOLOCK) ON projects_records.assigned = users_assigned.userid
LEFT OUTER JOIN dbo.users users_assigneddev WITH (NOLOCK) ON projects_records.assigneddev = users_assigneddev.userid
LEFT OUTER JOIN dbo.users users_assignedqa WITH (NOLOCK) ON projects_records.assignedqa = users_assignedqa.userid
LEFT OUTER JOIN dbo.users users_assignedsponsor WITH (NOLOCK) ON projects_records.assignedsponsor = users_assignedsponsor.userid
LEFT OUTER JOIN dbo.users users_createuser WITH (NOLOCK) ON projects_records.createuser = users_createuser.userid
LEFT OUTER JOIN dbo.clientusers clientusers_createuser WITH (NOLOCK) ON projects_records.createuser = clientusers_createuser.userid
LEFT OUTER JOIN dbo.projects_history_assignment WITH (NOLOCK) ON projects_history_assignment.recordid = projects_records.recordid
AND projects_history_assignment.historyid = (
SELECT ro.historyid
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.historyid
FROM rows rc
JOIN rows rn
ON rn.recordid = rc.recordid
AND rn.rn = rc.rn + 1
AND rn.assigned <> rc.assigned
WHERE rc.recordid = rl.recordid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
AND rl.recordid = projects_records.recordid
)
WHERE
(#assignedtype='0' and projects_records.assigned = #assigned)
OR (#assignedtype='1' and projects_records.assigneddev = #assigned)
OR (#assignedtype='2' and projects_records.assignedqa = #assigned)
OR (#assignedtype='3' and projects_records.assignedsponsor = #assigned)
OR (#assignedtype='4' and projects_records.createuser = #assigned)

WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY ticketid ORDER BY savedate DESC) AS rn
FROM #Table
)
SELECT projects_records.recordid,
projects_records.recordtype,
/* skipped */
AND projects_history_assignment.historyid = (
SELECT ro.historyid
FROM rows rl
CROSS APPLY
(
SELECT TOP 1 rc.savedate
FROM rows rc
JOIN rows rn
ON rn.recordid = rc.recordid
AND rn.rn = rc.rn + 1
AND rn.assigned <> rc.assigned
WHERE rc.recordid = rl.recordid
ORDER BY
rc.rn
) ro
WHERE rl.rn = 1
AND rl.recordid = projects_records.recordid
)

Well, if that query does not work out -- you could always consider a trigger on the tickets_history_assignment table. You could use INSTEAD OF INSERT, UPDATE which fires before any changes are made, so you would have full control of what is about to change and what to do.

Related

Where Clause Using Conditional Statement

i have query below
SELECT #RoleUser = MR.Code FROM MasterRole MR INNER JOIN MasterUsersRole MUR ON MR.Id = MUR.RoleId
INNER JOIN MasterUsers MU ON Mu.UserCode = MUR.UserCode
WHERE MU.UserCode = #UserLoginID
select 1 Num
, MyHistory.ID
, MyHistory.RequestNumber
, MyHistory.FlowID
, MyHistory.FlowProcessStatusID
from
(
select *
from Requests R
inner join
(
--DECLARE #UserLoginID nvarchar(200) = 'dum.testing.3'
select distinct
RequestID
from dbo.RequestTrackingHistory RTH
where IIF(#UserLoginID = 'admin', #UserLoginID, RTH.CreatedBy) = #UserLoginID
OR ( CreatedBy IN
SELECT Mu.UserCode from MasterUsers MU
INNER JOIN MasterUsersRole MUR ON MU.UserCode = MUR.UserCode
INNER JOIN MasterRole MR ON MUR.RoleId = MR.Id
WHERE MR.Code = #RoleUser
)
)
) RT on R.ID = RT.RequestID
) as MyHistory
inner join MasterFlow F on MyHistory.FlowID = F.ID
inner join
(
select FP.ID
, FP.Name
, FP.AssignType
, FP.AssignTo
, FP.IsStart
, case FP.AssignType
when 'GROUP' then
G.Name
end as 'AssignToName'
from MasterFlowProcess FP
left join dbo.MasterRole G on FP.AssignTo = G.ID and FP.AssignType = 'GROUP'
) FP on MyHistory.FlowProcessID = FP.ID
inner join MasterFlowProcessStatus FPS on MyHistory.FlowProcessStatusID = FPS.ID
left join MasterFlowProcessStatusNext FPSN on FPS.ID = FPSN.ProcessStatusFlowID
left join MasterFlowProcess FPN on FPSN.NextProcessFlowID = FPN.ID
left JOIN MasterRole MR ON MR.Id = FPN.AssignTo
left join MasterUsersRole MUR on MR.Id = MUR.RoleId
left join MasterUsers MURO on MUR.UserCode = MURO.UserCode
inner join MasterUsers UC on MyHistory.CreatedBy = UC.UserCode
left join MasterUsers UU on MyHistory.UpdatedBy = UU.UserCode
LEFT JOIN RequestMT RMT ON MyHistory.ID = RMT.RequestID
LEFT JOIN RequestGT RGT ON MyHistory.ID = RGT.RequestID
left join (SELECT sum(QtyCU) countQty , RequestId from dbo.RequestGTDetail where IsActive = 1 group by RequestId) RGTD on RGTD.RequestId = RGT.RequestId
left join (SELECT sum(QtyPCS) countQty , RequestId from dbo.RequestMTDetail where IsActive = 1 group by RequestId) RMTD on RMTD.RequestId = RMT.RequestId
left join (SELECT COUNT(IIF(returnable = 0, returnable, null)) countReturnable , RequestId from dbo.RequestMTDetail group by RequestId) RMTR on RMTR.RequestId = RMT.RequestId
left JOIN dbo.MasterDistributor md ON md.Code = RGT.CustId or md.Code = RMT.CustId
left JOIN dbo.MasterUsersDistributor MUD ON MUD.UserCode = MURO.UserCode AND md.Code = MUD.DistributorCode
LEFT JOIN dbo.MasterReason MRMT ON RMT.ReasonId = MRMT.Id
LEFT JOIN dbo.MasterReason MRGT ON RGT.ReasonId = MRGT.Id
LEFT JOIN dbo.MasterDistributorGroup MDG ON MDG.Id = MD.GroupId
OUTER APPLY dbo.FnGetHistoryApproveDate(MyHistory.Id) AS x
where REPLACE(FPS.Name, '#Requestor', uc.Name) <> 'DRAFT'
AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
i want to add some logic in where clause
this line
==> AND MUD.DistributorCode IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = #UserLoginID)
it depend on the #RoleUser variable, if #RoleUser IN ('A','B') then where clause above is executed, but if #RoleUser Not IN ('A','B') where clause not executed
i,m trying this where clause
AND IIF(#RoleUser IN ('A','B'), MUD.DistributorCode, #RoleUser) IN (SELECT DistributorCode FROM dbo.MasterUsersDistributor WHERE UserCode = IIF(#RoleUser IN ('A','B'), #UserLoginID, NULL))
it didn't work, only executed if #RoleUser IS ('A','B') other than that it return 0 record
any help or advice is really appreciated
thank you
The cleanest way I'm implemented these kind of crazy rules is a
holderTable
and a countVariable against the holder table.
I'll give a generic examples.
This is a "approach" and "philosophy", not a specific answer....with complex WHERE clauses.
DECLARE #customerCountryCount int
DECLARE #customerCountry TABLE ( CountryName varchar(15) )
if ( "the moon is blue on tuesday" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Honduras" UNION ALL SELECT "Malaysia"
END
if ( "favorite color = green" ) /* << whatever rules you have */
BEGIN
INSERT INTO #customerCountry SELECT "Greenland" UNION ALL SELECT "Peru"
END
SELECT #customerCountryCount = COUNT(*) FROM #customerCountry
Select * from dbo.Customers c
WHERE
(#customerCountryCount = 0)
OR
( exists (select null from #customerCountry innerVariableTable where UPPER(innerVariableTable.CountryName) = UPPER(c.Country) ))
)
This way, instead of putting all the "twisted logic" in an overly complex WHERE statement..... you have "separation of concerns"...
Your inserts into #customerCountry are separated from your use of #customerCountry.
And you have the #customerCountryCount "trick" to distinguish when nothing was used.
You can add a #customerCountryNotExists table as well, and code it to where not exists.
As a side note, you may want to try using a #temp table (instead of a #variabletable (#customerCountry above)... and performance test these 2 options.
There is no "single answer". You have to "try it out".
And many many variables go into #temp table performance (from a sql-server SETUP, not "how you code a stored procedure". That is way outside the scope of this question.
Here is a SOF link to "safe" #temp table usage.
Temporary table in SQL server causing ' There is already an object named' error

scalar variable error after it has been declared

I'm running Microsoft SQL Server 17.7 and I keep getting an error message when trying to filter my data set by a date range with a where clause using a scalar variable. I declared both variables but I continue to get this error message "Must declare the scalar variable "#startDate". I'm guessing I'm not declaring the scalar variable correctly. Please assist.
DECLARE #MatterList NVARCHAR(100) = '(21940-00035)'
declare #startDate datetime = '1/1/2012'
declare #endDate datetime = '6/30/2015'
SELECT #MatterList = NULL
WHERE #MatterList = ''
DROP TABLE IF EXISTS #listMatter
DROP TABLE IF EXISTS #Matterlist
CREATE TABLE #MatterList (rowid int identity, MatterNumber nvarchar(20))
CREATE INDEX tMatterListIndex_MatterNumber on #MatterList (MatterNumber)
select value into #listMatter from
string_split(replace(replace(replace(#MatterList,'(',''),')',''), ' ' , ''), ',')
Insert into #MatterList (MatterNumber)
select m.Number as MatterNumber
from #listMatter lm
inner join Matter m with (nolock) on lm.value = m.Number
where m.Number not in (select matterNumber from #MatterList)
If OBJECT_ID('tempdb..#fees_detail') is not NULL drop table #fees_detail
GO
SELECT DISTINCT 'Fees' AS [type],
t.code AS tudef2,
tc.PostDate AS bfindt,
tc.IsActive AS isActive,
tc.IsNoCharge AS isNoCharge,
m.OpenDate AS mopendt,
m.CloseDate AS mclosedt,
m.ContactInfo AS 'matter_contact',
a.DESCRIPTION AS 'matter_arrangement',
m.BillingInstruc AS 'billing_instructions',
m.Comments AS 'terms',
m.Number AS 'matter_id',
c.DisplayName AS 'client_name',
m.DisplayName AS 'matt_desc',
m.Narrative_UnformattedText AS 'matt_nar',
btk.Number AS 'batty_id',
btk.DisplayName AS 'batty_name',
tk.Number AS 'tk_id',
tk.DisplayName AS 'tk_name',
td.HireDate AS 'tkemdate',
title.DESCRIPTION AS 'tktitle',
htitle.DESCRIPTION AS 'htitle',
CASE htitle.DESCRIPTION
WHEN 'partner'
THEN 1
WHEN 'associate'
THEN 2
WHEN 'summer assoc.'
THEN 3
WHEN 'staff counsel'
THEN 4
WHEN 'paralegal'
THEN 5
WHEN 'als'
THEN 6
WHEN 'CSS admin'
THEN 7
WHEN 'legal graphics'
THEN 8
WHEN 'library'
THEN 9
WHEN 'case clerks'
THEN 10
WHEN 'lit analyst'
THEN 11
ELSE 12
END AS 'tktitle_sort',
d.DESCRIPTION AS 'mdept',
pg.DESCRIPTION AS 'mprac',
o.DESCRIPTION AS 'mloc',
tc.TimeIndex AS 't_index',
tc.WorkDate AS 'worked_date',
CONVERT(VARCHAR(6),tc.workdate,112) AS 'worked_period',
tc.WorkHrs AS 'tworkhrs',
tc.WorkRate AS 'tworkrt',
tc.WorkAmt AS 'tworkdol',
tc.WIPRemoveDate AS 'tbilldt',
tc.WIPHrs AS 'tbillhrs',
tc.WIPRate AS 'tbillrt',
tc.WIPAmt AS 'tbilldol',
tc.Narrative_UnformattedText AS 'time_desc',
'' AS 'ccode',
'' AS 'codesc1',
CASE
WHEN tc.IsNB = 1
THEN 0.00
ELSE tc.WIPAmt - tc.WorkAmt
END AS 'adj'
INTO #fees_detail
FROM timecard tc WITH (NOLOCK)
INNER JOIN matter AS m WITH (NOLOCK)
ON tc.matter = m.mattindex
INNER JOIN #MatterList AS tm
ON m.Number = tm.MatterNumber
INNER JOIN mattdate AS md WITH (NOLOCK)
ON m.MattIndex = md.MatterLkUp
AND CONVERT(DATE,GETDATE()) BETWEEN md.NxStartDate AND md.NxEndDate
INNER JOIN client AS c WITH (NOLOCK)
ON m.client = c.ClientIndex
INNER JOIN PracticeGroup AS pg WITH (NOLOCK)
ON md.PracticeGroup = pg.Code
INNER JOIN Department AS d WITH (NOLOCK)
ON md.Department = d.Code
INNER JOIN Arrangement AS a WITH (NOLOCK)
ON md.Arrangement = a.Code
INNER JOIN Office AS o WITH (NOLOCK)
ON md.Office = o.Code
INNER JOIN Timekeeper AS tk WITH (NOLOCK)
ON tc.Timekeeper = tk.TkprIndex
INNER JOIN TkprDate AS td WITH (NOLOCK)
ON tk.TkprIndex = td.TimekeeperLkUp
AND CONVERT(DATE,GETDATE()) BETWEEN td.NxStartDate AND td.NxEndDate
INNER JOIN TkprDate AS htd WITH (NOLOCK)
ON tk.TkprIndex = htd.TimekeeperLkUp
AND tc.WorkDate BETWEEN htd.NxStartDate AND htd.NxEndDate
INNER JOIN Timekeeper AS btk WITH (NOLOCK)
ON md.BillTkpr = btk.TkprIndex
INNER JOIN title WITH (NOLOCK)
ON td.title = title.code
INNER JOIN title AS htitle WITH (NOLOCK)
ON htd.title = htitle.code
LEFT OUTER JOIN task AS t WITH (NOLOCK)
ON tc.Task = t.TaskID
Where tc.WorkDate between #startDate and #enddate
ORDER BY m.Number, tc.WorkDate, tc.TimeIndex
SELECT
[type], tudef2, bfindt, isActive, isNoCharge, mopendt, mclosedt, matter_contact,
matter_arrangement, billing_instructions, terms, matter_id, client_name, matt_desc, matt_nar,
batty_id, batty_name, tk_id, tk_name, tkemdate, tktitle, htitle, tktitle_sort, mdept, mprac,
mloc, t_index, worked_date, worked_period, tworkhrs, tworkrt, tworkdol, tbilldt, tbillhrs,
tbillrt, tbilldol, time_desc, ccode, codesc1, adj
FROM #fees_detail
ORDER BY 29
GO flags the end of a batch of statements, i.e. everything from the beginning of the file (or the previous GO) is sent as one batch, and executed; this was probably ok, then everything following GO until the end of the file or the next GO is sent and executed, when this happened your declarations were already gone (not part of this batch. Remove GO.

Unexplainable SQL behaviour

I have a simple SQL query, with a handful of joined queries.
In my select I have a function shaping the date to a string format as below
LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
The script I am running should return 84 rows currently, but when executing the above in the select, it continuosly returns a different volume of rows every execution? there are no changes to the underlying tables between executions.
The strange thing is that whe I swith this back to a standard date conversion, the rows total 84
CONVERT(DATETIME,CONVERT(NVARCHAR,ADM_DT)+' '+ADM_TM)
Can anyone explain why SQL is behaving this way, I have not seen this before?
Full script below:
SELECT
[Visit ID] = a050.HSP_NO
,[Current Site] = currwd.HOSP
,[Current Specialty] = curr.SPEC
,[Current Ward] = currwd.WARD
,[Current Ward Name] = REPLACE(currwd.CURRDESC,'"','')
,[Current Consultant] = curr.PROF
,[Admission Date] = LEFT(REPLACE(ADM_DT,'-',''),8)+REPLACE(ADM_TM,':','')+'00'
,[Active] = '1'
,[PAS ID] = [crn].[crn]
,[Patient Class] = 'IP'
,NHS.[nhsno]
,CHI.CHI
,CASE WHEN OSV.X_CN IS NOT NULL THEN 'OSV' ELSE '' END OSV
,CASE WHEN NHS.[nhsno] LIKE '7%' THEN '7 NHSNO' ELSE '' END [PROBLEM NHS NO]
,DATEDIFF(D,PATS.DATE_OF_BIRTH,CONVERT(DATE,ADM_DT)) /365 [AGE ON ADMISSION]
FROM PCSSSA..SILVER.APK050_HPROVSPELL a050 WITH (NOLOCK)
-- Current Admission details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, SPEC, PROF --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)curr
ON curr.X_CN = a050.X_CN
AND a050.HSP_NO = curr.HSP_NO
AND curr.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO DESC)
-- Current Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN, CEP_NO ORDER BY WS_NO DESC) AS WR
FROM PCSSSA..SILVER.APK052_WARDSTAY wdstay WITH (NOLOCK)
LEFT JOIN (SELECT
CURRWARD = OBJ_LOC,
CURRDESC = OBJ_DESC
FROM [PCSSSA]..[SILVER].[ENV030_LOCDETS] WITH (NOLOCK)
WHERE OBJ_TYPE = 'WARD'
AND DATE_TO IS NULL
)wdname
ON wdstay.WARD = wdname.CURRWARD
) currwd
ON curr.X_CN = currwd.X_CN
AND curr.CEP_NO = currwd.CEP_NO
AND currwd.WR=1
--- Admitting details
LEFT JOIN (
SELECT X_CN, CEP_NO, HSP_NO, PROF, SPEC --MSPEC
FROM PCSSSA..SILVER.APK051_CONEPIS epi WITH (NOLOCK)
-- Main Specialty Map
LEFT JOIN PCSSSA..SILVER.ENV050_DISCIPDETS en050 WITH (NOLOCK)
ON epi.SPEC = en050.OBJ_DISC
AND en050.OBJ_TYPE='SP'
AND en050.DATE_TO IS NULL
)adm
ON adm.X_CN = a050.X_CN AND a050.HSP_NO = adm.HSP_NO
AND adm.CEP_NO = (SELECT TOP 1 a051.CEP_NO
FROM PCSSSA..SILVER.APK051_CONEPIS a051 WITH (NOLOCK)
Where a051.X_CN = a050.X_CN AND a050.HSP_NO = a051.HSP_NO
Order By CEP_NO)
-- Admitting Ward Detail
JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY X_CN,CEP_NO ORDER BY WS_NO) AS WR FROM PCSSSA..SILVER.APK052_WARDSTAY WITH (NOLOCK)) admwd
ON adm.X_CN = admwd.X_CN
AND adm.CEP_NO = admwd.CEP_NO
AND admwd.WR=1
-- Patient Detail
LEFT JOIN
(SELECT
[id].[RM_PATIENT_NO],
[id].[NUM_ID_TYPE] + CONVERT(NVARCHAR,[NUMBER_ID]) [crn]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('0', '1', 'W')
)[crn]
ON a050.[X_CN] = [crn].[RM_PATIENT_NO]
-- NHS NUMBERS
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [nhsno]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] = ('NHS')
)NHS
ON NHS.RM_PATIENT_NO = a050.X_CN
-- CHI NUMBER
LEFT JOIN
(
SELECT
[id].[RM_PATIENT_NO],
[id].[NUMBER_ID] [CHI]
FROM [PCSSSA]..[SILVER].[NUMBER_IDS] [id] WITH (NOLOCK)
WHERE [id].[NUM_ID_TYPE] IN ('CHI')
)CHI
ON CHI.RM_PATIENT_NO = a050.X_CN
-- OVERSEES STATUS
LEFT JOIN
(
SELECT X_CN, [STATUS], SDATE, EDATE FROM PCSSSA..SILVER.CRS037_OSV_STATUS WITH (NOLOCK)
)OSV
ON OSV.X_CN = a050.X_CN
AND CONVERT(DATE,ADM_DT) >= OSV.SDATE
AND (OSV.SDATE IS NULL
OR CONVERT(DATE,ADM_DT) <= OSV.EDATE)
-- DEMOGRAPHICS
LEFT JOIN
(
SELECT RM_PATIENT_NO, DATE_OF_BIRTH FROM PCSSSA..[SILVER].[PATIENTS] WITH (NOLOCK)
)PATS
ON PATS.RM_PATIENT_NO = a050.X_CN
-- CURRENTLY ADMITTED ONLY
WHERE DIS_DT IS NULL
-- WITHOUT NHS NUMBER
AND (nhsno IS NULL
-- OR BRING IN ANY 7 NHS NUMBERS FOR CORRECTION
OR NHS.[nhsno] LIKE '7%'
-- ALSO INCLUDE OVERSEES
OR OSV.X_CN IS NOT NULL)
What is even stranger, is that if you wrap this in a subquery and coun(*) on the outer then it totals 84 as expected, very strange!

Excluding rows derived from case statement with a specific value based on values from another column

How do I exclude rows with a specific value in a field based on specific values of another field? To dive deeper:
I have a column called "rule_name" that's derived from a case statement.
I have another column called "DeliveryTermsIdentifier" that's pulled from another table (see image of query result below).
I'm trying to remove rows with rule_name "Delivery event required" only if DeliveryTermsIdentifier is "PP", "DA", ect. I'm getting thrown off because my rule_name column is based off a condition already.
image of query result
Here is the SQL used to derive those 2 columns:
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid
One way is to put what you have in a subquery and filter out with a where clause in the outer query. E.g.
SELECT rule_name, reporting_result, DeliveryTermsIdentifier
FROM
(SELECT 'X'
,case when s.ShipmentNo is not null then cast(dqr.rulename as varchar(30))
else cast(dqc.dataqualityruleid as varchar(30)) end as rule_name
,case when (dqd.SuccessFlag = 0) then 'Missing'
when (dqd.SuccessFlag = 1) then 'Reported'
when (s.ShipmentNo is null) then 'Missing' end reporting_result
,s.DeliveryTermsIdentifier
from CustomerMasterList cml
join organization o on o.organizationid = cml.senderid
inner join DataQualityConfig dqc on dqc.DomainId = cml.DomainID
left outer join shipment s on s.shipmentno = cml.shipmentno
left outer join dataqualityresult dqd on dqd.shipmentid = s.shipmentid
left outer join dataqualityrule dqr on dqr.dataqualityruleid
=dqd.dataqualityruleid ) AS sub
WHERE DeliveryTermsIdentifier NOT IN ('PP', 'DA') AND rule_name <> 'Delivery event required'
You can also encapsulate your case statements into an outer apply and use the alias like this:
SELECT * ,
rules.rule_name ,
RESULT.reporting_result ,
s.DeliveryTermsIdentifier
FROM CustomerMasterList cml
JOIN organization o ON o.organizationid = cml.senderid
INNER JOIN DataQualityConfig dqc ON dqc.DomainId = cml.DomainID
LEFT OUTER JOIN shipment s ON s.shipmentno = cml.shipmentno
LEFT OUTER JOIN dataqualityresult dqd ON dqd.shipmentid = s.shipmentid
LEFT OUTER JOIN dataqualityrule dqr ON dqr.dataqualityruleid = dqd.dataqualityruleid
OUTER APPLY ( SELECT CASE WHEN ( dqd.SuccessFlag = 0 ) THEN 'Missing'
WHEN ( dqd.SuccessFlag = 1 ) THEN 'Reported'
WHEN ( s.ShipmentNo IS NULL ) THEN 'Missing'
END reporting_result ) RESULT
OUTER APPLY ( SELECT CASE WHEN s.ShipmentNo IS NOT NULL THEN
CAST(dqr.rulename AS VARCHAR(30))
ELSE
CAST(dqc.dataqualityruleid AS VARCHAR(30))
END AS rule_name ) rules
WHERE s.DeliveryTermsIdentifier NOT IN ( 'PP', 'DA' )
AND rules.rule_name <> 'Delivery event required';

Remove duplicate address_id from sql data set

I need to get only distinct address_id in result no duplication. Here is my query.
SELECT DISTINCT address.address_id, address.address1, address.streetcity, state.stateabbrev, rtrim(ltrim(case when address.streetzipcode is not null and address.streetzipcode != 'NULL' then address.streetzipcode else '' end))+case when len(address.streetzipplus4)>0 then '-'+rtrim(ltrim(address.streetzipplus4)) else '' end as streetzipcode, address.homephone,
dbo.f_addressstudent (student.address_id) as Students,
dbo.f_addresspeople (student.address_id) as Adults,
case
when #classif_id IS NULL then 0
else
student.classif_id
end classif,
classifctn
FROM district WITH(NOLOCK)
JOIN dbo.building ON building.district_id = district.district_id
JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
JOIN dbo.student WITH(NOLOCK) ON student.student_id = studbldg_bridge.student_id
JOIN classif with(nolock) on student.classif_id = classif.classif_id
LEFT JOIN dbo.address WITH(NOLOCK) ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK) ON address.streetstate_id = state.state_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
WHERE district.district_id = (SELECT district_id FROM dbo.building WITH(NOLOCK) WHERE bldg_id = #bldg_id)
ORDER BY classif,Adults, Students
Here is result of query
Query result with error in data
I have tried to group by and use aggregate function with address_id but I also have non-aggregate columns so it didn't worked for me.
After that I also tried using OVER(partition by address.address_id) but it also didn't worked.
Any help will be appreciated in advance.
Thank you
**UPDATE on Business logic/Requirements **
I need to get unique addresses for parents of students. As parent can have two or more children living in same address, it causes duplication. I need to get only one child per parent in other words.
From your image of the results it looks like the classifctn column has more than 1 value so it is repeating your row by that. In order to get 1 distinct address_id and rest of the columns either remove it from your query or you can set a precedence that will only return 1 record per address_id
further please tag only the RDBMs you ware actually using. MySQL for example doesn't have window functions yet you tagged it yet referenced using OVER(partition.... which would not be possible in mysql
;WITH cte (
SELECT DISTINCT address.address_id, address.address1, address.streetcity, state.stateabbrev, rtrim(ltrim(case when address.streetzipcode is not null and address.streetzipcode != 'NULL' then address.streetzipcode else '' end))+case when len(address.streetzipplus4)>0 then '-'+rtrim(ltrim(address.streetzipplus4)) else '' end as streetzipcode, address.homephone,
dbo.f_addressstudent (student.address_id) as Students,
dbo.f_addresspeople (student.address_id) as Adults,
case
when #classif_id IS NULL then 0
else
student.classif_id
end classif,
classifctn,
ROW_NUMBER() OVER (PARTITION BY address.address_id ORDER BY HOW WILL YOU CHOOSE?) AS RowNum
FROM district WITH(NOLOCK)
JOIN dbo.building ON building.district_id = district.district_id
JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
JOIN dbo.student WITH(NOLOCK) ON student.student_id = studbldg_bridge.student_id
JOIN classif with(nolock) on student.classif_id = classif.classif_id
LEFT JOIN dbo.address WITH(NOLOCK) ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK) ON address.streetstate_id = state.state_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
WHERE district.district_id = (SELECT district_id FROM dbo.building WITH(NOLOCK) WHERE bldg_id = #bldg_id)
)
SELECT *
FROM
cte
WHERE
RowNum = 1
ORDER BY
classif
,Adults
,Students
Alternatively you could nest your select query. note though this solution is somewhat useless as it will only return 1 grade/classifctn when more than 1 exists in a household if you really don't care about the column then you should just remove it from your query.
Actually both your classifctn and classif columns will cause you multiple rows when more than 1 student is at the same address. here is a way to concatenate those values to a single row. You should spend some more time on your business case and defining it for us. But here is one example for you:
SELECT DISTINCT
address.address_id
,address.address1
,address.streetcity
,state.stateabbrev
,LTRIM(RTRIM(ISNULL(NULLIF(address.streetzipcode,'NULL'),'')))
+ CASE WHEN LEN(address.streetzipplus4) > 0 THEN '-' ELSE '' END
+ LTRIM(RTRIM(ISNULL(address.streetzipplus4,''))) AS streetzipcode
,address.homephone
,dbo.f_addressstudent (student.address_id) as Students
,dbo.f_addresspeople (student.address_id) as Adults
, case
when #classif_id IS NULL then 0
else student.classif_id
end classif
,STUFF(
(SELECT ',' + CAST(classif_id AS VARCHAR(100))
FROM
classif c
WHERE c.classif = student.classif
FOR XML PATH(''))
,1,1,'') AS classifs
,STUFF(
(SELECT ',' + CAST(classifctn AS VARCHAR(100))
FROM
classif c
WHERE c.classif = student.classif
FOR XML PATH(''))
,1,1,'') AS classifctns
FROM
district WITH(NOLOCK)
INNER JOIN dbo.building
ON building.district_id = district.district_id
AND building.bldg_id = #bldg_id
INNER JOIN dbo.student WITH(NOLOCK)
ON student.student_id = studbldg_bridge.student_id
INNER JOIN dbo.address WITH(NOLOCK)
ON student.address_id = address.address_id
LEFT JOIN dbo.state WITH(NOLOCK)
ON address.streetstate_id = state.state_id
Note I when ahead and changed the zip code logic to show you some use of ISNULL() and NULLIF() that are helpful in cases like that. I also removed 3 tables because 2 are not used and the third ends up being used in a subselect to concatenate the values. Also address table was changed to an INNER JOIN because if an address doesn't exist all of the other information becomes blank/useless....
INNER JOIN dbo.studbldg_bridge WITH(NOLOCK) ON studbldg_bridge.bldg_id=building.bldg_id
LEFT JOIN dbo.state AS mailstate WITH(NOLOCK) ON address.state_id = mailstate.state_id
INNER JOIN classif with(nolock) on student.classif_id = classif.classif_id