Getting TFS work items on SSMS - sql-server

I need some help mimicking a TFS query.
I have tried writing the following SQL query to do so but I am not able to get a matching population:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id
, LastUpdatedDateTime = MAX(LastUpdatedDateTime)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
SELECT distinct ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Current'
WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-14,CONVERT(Date,getdate(),1)) AND Microsoft_VSTS_Common_ClosedDate < dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Last'
ELSE 'Previous' END
, TSRNumber = Custom_TSRNumber
FROM
(Select * from (select *, rn = row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc)
from dbo.DimWorkItem w1) d where rn = 1) w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.LastUpdatedDateTime = l.LastUpdatedDateTime
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
WHERE System_WorkItemType = 'Task'
AND da.AreaPath like '\LOS\Reporting%'
AND w.Microsoft_VSTS_Common_Priority < 4
Also if anyone knows where I could find the department field as I am not sure whether it is a custom field or not.
SQL Server 2014: 12.0
TFS: 12.0
Visual studio professional 2015: 14.0
Thank you in advance for your suggestions!

I found a solution although still not able to find the the Department field :
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id, LastChangedDate = MAX(System_ChangedDate)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
DECLARE #FromDateWeek DATE
DECLARE #FromDateTwoWeek DATE
SET #FromDateWeek = dateadd(d,-7,CONVERT(Date,getdate(),1))
SET #FromDateTwoWeek = dateadd(d,-14,CONVERT(Date,getdate(),1))
--SELECT #FromDate
SELECT ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN w.Microsoft_VSTS_Common_ClosedDate >= #FromDateWeek OR w.System_State = 'Active' THEN 'Current'
WHEN (w.Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek AND w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek)
OR w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek THEN 'Last'
ELSE 'Previous' END
FROM [dimWorkItem] w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.System_ChangedDate = l.LastChangedDate
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
WHERE
da.AreaPath LIKE '\LOS\Reporting%'
AND System_WorkItemType = 'Task'
AND (Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek
OR w.System_State = 'Active')
AND ISNULL(Microsoft_VSTS_Common_Priority,0) < 4
AND w.System_Reason <> 'Obsolete'

Related

Select top 1 subquery with parameters (SQL)

I am removing a user function which finds shows item prices based on configurations but the function is too slow.
Therefore I'm trying to write a query to do the same. This query finds the latest price that matches the required criteria
This is kind of what I'm going for but I cannot figure out how to handle this requirement correctly:
(Intellisesnse says s.inventdimid does not exist in the h subquery)
SELECT s.salesid
,s.itemid
,h.price
FROM salesline s
LEFT OUTER JOIN (
SELECT TOP 1 p.price
,p.itemid
,p.dataareaid
,l.inventdimid
FROM inventitemprice p
JOIN inventdim d ON d.dataareaid = p.dataareaid
AND d.inventdimid = p.inventdimid
JOIN inventdim l ON l.dataareaid = p.dataareaid
AND (
l.configid = d.configid
OR d.configid = ''
)
AND (
l.inventcolorid = d.inventcolorid
OR d.inventcolorid = ''
)
AND (
l.inventsizeid = d.inventsizeid
OR d.inventsizeid = ''
)
AND (
l.inventstyleid = d.inventstyleid
OR d.inventstyleid = ''
)
AND (p.ACTIVATIONDATE < getdate())
AND l.inventsiteid = d.inventsiteid
WHERE pricetype = 0
AND l.inventdimid = s.inventdimid /* <========= */
AND p.dataareaid = 'lkc'
ORDER BY activationdate DESC
,d.configid DESC
,d.inventcolorid DESC
,d.INVENTSIZEID DESC
,d.inventstyleid DESC
) AS h ON h.itemid = s.itemid
AND h.DATAAREAID = s.DATAAREAID
AND h.INVENTDIMID = s.inventdimid
WHERE s.dataareaid = 'lkc'
AND s.SALESSTATUS = 1
What would be the appropriate method for querying this?

How to get a windowed function working in WHERE clause

I know that there are quite many threads on "Windowed functions can only appear in the select or ORDER BY clases" topic, but I have read them through and just don't seem to get any of those trick to work for me. So here I go.
My Query you can see below the line. I have highlighted the part of the Query which is "causing" me issues or problems. The thing is that I would like to get
"LocalCurrentAmount not between -1.000000 and 1.000000"
in somehow. I have tried the CTE versioon, but somehow didn't work and my declare tables and then the details view started causing problems.
Would really appreciate your help!
Jaanis
declare #exceptions1 table (CustomerCode varchar(7), Exception_comment varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(3514437,'Exception'),(3500977,'Exception'),(3295142,'Exception'), ...
declare #exceptions2 table (CustomerCode2 varchar(7), Exception_comment2 varchar(15));
insert into #exceptions2 (CustomerCode2, Exception_comment2)
VALUES
(3390437,'VIP SE') ,(3390438,'VIP SE') ,(3390481,'VIP SE'), ...
declare #exceptions3 table (CustomerCode3 varchar(7), Exception_comment3 varchar(15));
insert into #exceptions1 (CustomerCode, Exception_comment)
VALUES
(1530350, 'DK Exception'), (1533834, 'DK Exception'), (1530002, 'DK Exception'), ...
with Details as
(
select ard.AccountsReceivableHeaderID, sum(ard.TransactionAmountOC) as DetailAmountOC , Max(DetailSequenceCode) as DetailSequenceCode, Max( ard.BatchDate) as BatchDate
from dmbase.fAccountsReceivableDetail ard
join dmbase.fAccountsReceivable arh on ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
where ard.BatchDate <= getdate()
group by AccountsReceivableHeaderID
)
SELECT
comp.CompanyCode
,convert(varchar(10),ar.InvoiceDate, 103) as Invoice_date -- dd/MM/yyyy format
,case
when ar.IsCreditMemo = 'Y' then 'Memo (Credit/Debit)'
when ar.InvoiceCode = '0' then 'Payment'
else 'Invoice'
end as Description
,isnull(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) InvoiceSummaryCode
,case
when len(ar.InvoiceSequenceCode) = '1' then CONCAT(ar.InvoiceCode,'-000',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '2' then CONCAT(ar.InvoiceCode,'-00',ar.InvoiceSequenceCode)
when len(ar.InvoiceSequenceCode) = '3' then CONCAT(ar.InvoiceCode,'-0',ar.InvoiceSequenceCode)
else CONCAT(ar.InvoiceCode,'-',ar.InvoiceSequenceCode)
end as Invoice#
,**(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+
coalesce(det.DetailAmountOC, 0)) * coalesce(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount**
,(ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end
+ coalesce(det.DetailAmountOC, 0)) AS CurrentAmount
,ar.OriginalInvoiceAmountOC
+
case
when row_number() over (partition by AccountsReceivableID order by ar.InvoiceCode) = 1 then isnull(vat.vatAdjustment, 0)
else 0
end as OriginalInvoiceAmountOC
,ar.InvoiceCurrencyCode
,cust.CustomerCode
,upper(cust.CustomerName) as CustomerName
from
dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc
ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust
ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat
on ar.InvoiceCode = vat.contractNumber
and ar.InvoiceSequenceCode = vat.invoiceSequence
and cust.CustomerCode = vat.CustomerNumber
and loc.CompanyCode = vat.companyCode
inner join dmbase.dCompany comp
on (ar.CompanyID = comp.CompanyID)
left join dmbase.dAccountsReceivableInvoiceStatus aris
on (aris.ARInvoiceStatusAMID=ar.ARInvoiceStatusAMID)
left hash join Details det
on (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
left join dmbase.dCurrencyExchangeRate cer
on (comp.CompanyCode = cer.CompanyCode
and ar.InvoiceCurrencyCode = cer.CurrencyCode
and case ar.InvoiceDate when '1900-01-01' then getdate() else ar.InvoiceDate end between cer.ValidFrom and cer.ValidTo)
left join dmbase.fContractClosedHeader ccd
on ccd.ContractNumber = ar.InvoiceCode
and ccd.ContractSeqNumber = ar.InvoiceSequenceCode
and ccd.CompanyID = ar.CompanyID
and ccd.ContractNumber!='0'
and ccd.CreditMemoContractNumber != '0'
left join dmbase.fAccountsReceivableHeader cm
on ccd.CreditMemoContractNumber = cm.ContractNumber
and ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
and cm.CompanyID = ccd.CompanyID
where
(aris.ARInvoiceStatusCode = 'OP' or (ar.LastPaymentDate >= getdate())
or (ar.TotalAdjustmentsAmountOC <> 0 and ar.CurrentAmountLC = 0
and (ar.OriginalInvoiceAmountOC + isnull(vat.vatAdjustment, 0) ) + coalesce(det.DetailAmountOC, 0) <> 0)
)
and ar.OriginalInvoiceAmountOC <= 0
and ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
and cust.InternalCustomerType = 'External'
and cust.CustomerName not in ('RR AJM', 'RAMIRENT', 'Ramirent')
and cust.CustomerName not like '%[7][0-9][0-9][0-9]%'
and ar.InvoiceDate <= EOMONTH(getdate(),-3
and cust.CustomerCode NOT IN
(select CustomerCode from #exceptions1
union
select CustomerCode2 from #exceptions2
union
select CustomerCode3 from #exceptions3)
order by Invoice_date
When using a Window function, like you said in your post, you can't use it in the WHERE clause. The common solution, therefore, is to use a CTE and reference it in the WHERE outside of it. I've used your CTE, however, without any kind of sample data this is a total guess. I've also left a lot of comments for you, and changed some other parts of the SQL, as some of the clauses you have will effect your query's performance.
WITH
Details AS
(SELECT ard.AccountsReceivableHeaderID,
SUM(ard.TransactionAmountOC) AS DetailAmountOC,
MAX(DetailSequenceCode) AS DetailSequenceCode,
MAX(ard.BatchDate) AS BatchDate
FROM dmbase.fAccountsReceivableDetail ard
JOIN dmbase.fAccountsReceivable arh ON ard.AccountsReceivableHeaderID = arh.AccountsReceivableID
WHERE ard.BatchDate <= GETDATE()
GROUP BY AccountsReceivableHeaderID),
Summary AS(
SELECT comp.CompanyCode,
CONVERT(varchar(10), ar.InvoiceDate, 103) AS Invoice_date, -- dd/MM/yyyy format
CASE
WHEN ar.IsCreditMemo = 'Y' THEN 'Memo (Credit/Debit)'
WHEN ar.InvoiceCode = '0' THEN 'Payment'
ELSE 'Invoice'
END AS Description,
ISNULL(cm.SummaryInvoiceCode, ar.InvoiceSummaryCode) AS InvoiceSummaryCode,
CASE
WHEN LEN(ar.InvoiceSequenceCode) = '1' THEN CONCAT(ar.InvoiceCode, '-000', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '2' THEN CONCAT(ar.InvoiceCode, '-00', ar.InvoiceSequenceCode)
WHEN LEN(ar.InvoiceSequenceCode) = '3' THEN CONCAT(ar.InvoiceCode, '-0', ar.InvoiceSequenceCode)
ELSE CONCAT(ar.InvoiceCode, '-', ar.InvoiceSequenceCode)
END AS Invoice#,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) * COALESCE(cer.CurrencyExchangeRate, ar.CurrencyExchangeRate) AS LocalCurrentAmount,
(ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END + COALESCE(det.DetailAmountOC, 0)) AS CurrentAmount,
ar.OriginalInvoiceAmountOC + CASE
WHEN ROW_NUMBER() OVER (PARTITION BY AccountsReceivableID ORDER BY ar.InvoiceCode) = 1 THEN ISNULL(vat.vatAdjustment, 0)
ELSE 0
END AS OriginalInvoiceAmountOC,
ar.InvoiceCurrencyCode,
cust.CustomerCode,
UPPER(cust.CustomerName) AS CustomerName
FROM dmbase.fAccountsReceivable ar
INNER JOIN dmbase.dlocation loc ON loc.LocationID = ar.LocationID
INNER JOIN dmbase.dCustomer cust ON cust.CustomerID = ar.CustomerID
LEFT JOIN dmbase.VatAdjustment vat ON ar.InvoiceCode = vat.contractNumber
AND ar.InvoiceSequenceCode = vat.invoiceSequence
AND cust.CustomerCode = vat.CustomerNumber
AND loc.CompanyCode = vat.companyCode
INNER JOIN dmbase.dCompany comp ON (ar.CompanyID = comp.CompanyID)
LEFT JOIN dmbase.dAccountsReceivableInvoiceStatus aris ON (aris.ARInvoiceStatusAMID = ar.ARInvoiceStatusAMID)
LEFT HASH JOIN Details det ON (ar.AccountsReceivableID = det.AccountsReceivableHeaderID)
LEFT JOIN dmbase.dCurrencyExchangeRate cer ON (comp.CompanyCode = cer.CompanyCode
AND ar.InvoiceCurrencyCode = cer.CurrencyCode
AND CASE ar.InvoiceDate WHEN '1900-01-01' THEN GETDATE()ELSE ar.InvoiceDate END BETWEEN cer.ValidFrom AND cer.ValidTo)
LEFT JOIN dmbase.fContractClosedHeader ccd ON ccd.ContractNumber = ar.InvoiceCode
AND ccd.ContractSeqNumber = ar.InvoiceSequenceCode
AND ccd.CompanyID = ar.CompanyID
AND ccd.ContractNumber != '0'
AND ccd.CreditMemoContractNumber != '0'
LEFT JOIN dmbase.fAccountsReceivableHeader cm ON ccd.CreditMemoContractNumber = cm.ContractNumber
AND ccd.CreditMemoSequenceCode = cm.ContractSeqNumber
AND cm.CompanyID = ccd.CompanyID
WHERE (aris.ARInvoiceStatusCode = 'OP'
OR (ar.LastPaymentDate >= GETDATE())
OR (ar.TotalAdjustmentsAmountOC <> 0
AND ar.CurrentAmountLC = 0
AND (ar.OriginalInvoiceAmountOC + ISNULL(vat.vatAdjustment, 0)) + COALESCE(det.DetailAmountOC, 0) <> 0)) --Why ISNULL for one, COALESCE for the other? Both will make the query non-SARGable
AND ar.OriginalInvoiceAmountOC <= 0
AND ar.IsCreditMemo = 'Y' -- ainult Memo (Credit/Debit)
AND cust.InternalCustomerType = 'External'
AND cust.CustomerName NOT IN ('RR AJM', 'RAMIRENT', 'Ramirent')
AND cust.CustomerName NOT LIKE '%[7][0-9][0-9][0-9]%' --A leading wildcard is going to perform slow
AND ar.InvoiceDate <= EOMONTH(DATEADD(DAY, -3, GETDATE())) --I have changed this from EOMONTH(GETDATE(), -3 (which made no sense)
AND NOT EXISTS (SELECT 1
FROM #exceptions1 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions2 E
WHERE E.CustomerCode = cust.CustomerCode) --Changed to EXISTS binned UNION (you should use UNION ALL if you're doing something like this, it'll be quicker)
AND NOT EXISTS (SELECT 1
FROM #exceptions3 E
WHERE E.CustomerCode = cust.CustomerCode)) --Changed to EXISTS binned UNION you should use UNION ALL if you're doing something like this, it'll be quicker)
SELECT *
FROM Summary
WHERE LocalCurrentAmount NOT BETWEEN -1 AND 1
ORDER BY Invoice_date;
It's worth noting that the above sql is completely untested. I do not have access to your server, or data, so I'm purely relying on "my eye" to note any errors.

how to check if password expiry column in a store procedure has only 14,7,3,2,1 days left?

i have an sp that i check if user's password change date has 14 days
left(flag=0) and i send email to that users and i that sp i check(by a
col.flag) if email already sent or not.after that i update the the
flag col.in an another SP(ExpiryNotificationFlag) to 1 of users list whose email has
already sent..now i don't know how to check for 7,3,2,1 days as flag
col value is already 1 ?
sp
SELECT TenantName
, TenantEmail
, GMAP_code
, ContactID FROM (
SELECT b_1.TenantName
, b_1.TenantEmail
, LastPDWChangeDate =(SELECT ISNULL(max (DateChanged),GETDATE()) FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID)
, ExpiryNotificationFlag =(SELECT top 1 ExpiryNotificationFlag FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID order by DateChanged desc)
, GMAP_code =(SELECT TOP 1 ISNULL(GMAP_CODE,'') from wsm_Ref_Buildings where BuildingId = b_1.BuildingID)
, b_1.TenantRegContactID as ContactID
FROM dbo.wsm_Contact AS a LEFT OUTER JOIN
(
SELECT C.Name AS TenantName
, A.SiteID
, A.BuildingID
, A.FloorID
, A.ContactID AS TenantRegContactID
, D.LEASID
, C.Phone AS TenantPhone
, C.Email AS TenantEmail
, B.UserID AS userid
, C.Mobile AS TenantMobile
, B.UserType
FROM dbo.wsm_Contact_Tenancy AS A
INNER JOIN dbo.wsm_Contact_User AS B ON A.ContactID = B.ContactID AND B.Active = 1
INNER JOIN dbo.wsm_Contact AS C ON B.ContactID = C.ContactID
INNER JOIN (
SELECT DISTINCT COALESCE (LEASID, ExtLeasNum) AS LEASID
, SiteID
, BuildingID
, FloorID
FROM dbo.wsm_Contact) AS D ON A.SiteID = D.SiteID AND A.BuildingID = D.BuildingID AND A.FloorID = D.FloorID) AS b_1 ON
COALESCE (a.LEASID, a.ExtLeasNum) = b_1.LEASID AND a.SiteID = b_1.SiteID AND a.BuildingID = b_1.BuildingID AND a.FloorID = b_1.FloorID
INNER JOIN dbo.wsm_Ref_Floors AS C ON a.FloorID = C.FloorId
WHERE (a.OCCPSTAT NOT IN ('I', 'P')) and C.Deleted = 0 and b_1.userid is not null ) AS A WHERE DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) <> 1
END
update Query
UPDATE dbo.wsm_Contact_PwdHistory set ExpiryNotificationFlag = 1 WHERE ContactID = #ContactID
you can do it like that
( (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) = 0) --14 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 83 AND ISNULL(ExpiryNotificationFlag,0) = 1) --7days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 87 AND ISNULL(ExpiryNotificationFlag,0) = 2) --3 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 88 AND ISNULL(ExpiryNotificationFlag,0) = 3) --2 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 89 AND ISNULL(ExpiryNotificationFlag,0) = 4) --1 day
)
for that u have to modify Expiry notification flag to int instead of a Boolean
after that make a SP where will u update the value from
0 to 1,1 to 2,2 to 3 etc.
Youre essentially making the following complaint:
"A boolean datatype can only store one of two values!"
Indeed, so swap out that flag for a "Number of Days Left" column, and compare it to 14, 7, whatever....
Note, ExpiryNotificationFlag column isn't a great name - how about "PasswordExpiryEmailSent"
Sometimes these problems get a lot easier to think about when the columns have better names

Duplicate fields in a table, distinct doesn't work

I have the following query:
select distinct
ROW_ID = row_number() over (
order by wms_us.wms_us.rrno.rrdate
, wms_us.wms_us.rrno.pono
, wms_us.wms_us.transferboxdet.meidhex
, att.Date_cleared
)
, ATT_PO = wms_us.wms_us.rrno.pono
, Received_Date = wms_us.wms_us.rrno.rrdate
, IMEI = case
when len(wms_us.wms_us.transferboxdet.meidhex) >= 15
then left(wms_us.wms_us.transferboxdet.meidhex, 14)
else wms_us.wms_us.transferboxdet.meidhex
end
, Model = case
when (wms_us.wms_us.model.modeldesc = 'MIXED')
then wms_us.wms_us.transferboxdet.basemodel
else wms_us.wms_us.model.modelbase
end
, Date_cleared = case
when (Future.[Error Code] = '1')
then Future.LocalTime
else att.Date_cleared
end
, Result = case
when (Future.[Error Code] = '1')
then 'PASS'
else att.Result
end
from wms_us.wms_us.transferboxdoc
inner join wms_us.wms_us.transferboxdet
on wms_us.wms_us.transferboxdoc.transferboxdocid
= wms_us.wms_us.transferboxdet.transferboxdocid
inner join wms_us.wms_us.rrno
on wms_us.wms_us.transferboxdet.rrnoid = wms_us.wms_us.rrno.rrnoid
inner join wms_us.wms_us.model
on wms_us.wms_us.transferboxdoc.modelid = wms_us.wms_us.model.modelid
left join DRSCSQLQADB01.att_view2.dbo.attview2 as att
on att.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
inner join Futerdial.dbo.Futuredial_Validation as Future
on Future.IMEI = wms_us.wms_us.transferboxdet.meidhex
where (wms_us.wms_us.rrno.rrdate > '2016-12-01')
and Future.IMEI = '352130070643357'
I have the IMEI in the table Futuredial_Validation duplicate, I have been trying to use the Distinct just to show me one IMEI but it's not working, there is any alternative that I can use?? Or I am using it wrong?
Attach a picture of what is showing me, I just one be able to see one the first one.
Screenshot
Thanks
For rows to be filtered out by distinct, all values must be the same. In this query it looks like you can just wrap the query in a CTE and filter on ROW_ID = 1.

SQL Query Using WITH common_table_expression Fails in Codeigniter but Not SQL Studio

I created a query in MS SQL Management Studio for SQL Server 2012 that uses common_table_expression to self join a table. It works correctly in MS SQL Studio but in Codeigniter no result or error is returned.
The query:
WITH rows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[CreateDate]) AS rn
FROM (
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'IV' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_IVTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
UNION ALL
SELECT a.[PatientID], a.[BGValue], a.[CreateDate], a.[HospitalUnit], 'MSHA' as 'Hospital', h.[system_name], f.[facility_code], f.[facility_name], 'SubQ' as 'Treatment'
FROM [Analytics].[dbo].[MSHA_SubQTreatment] a
JOIN [Analytics].[dbo].[MSHA_Patients] p
ON p.[PatientID] = a.[PatientID]
JOIN [Analytics].[dbo].[Facilities] f
ON f.[facility_code] = p.[facility_code]
JOIN [Analytics].[dbo].[Hospitals] h
ON f.[hospital] = h.[hospital]
WHERE a.[CreateDate] BETWEEN '2013-05-01' AND '2013-05-31'
) u
)
SELECT mc.[PatientID], mc.[BGValue], mc.[CreateDate], mc.[Hospital], mc.[system_name] as 'System', mc.[facility_code], mc.[facility_name], mc.[HospitalUnit], DATEDIFF(second, mp.[CreateDate], mc.[CreateDate])/60 as 'Interval', mc.[Treatment]
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn + 1 and mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[CreateDate] ASC;
When I put that into a variable and attempt to retrieve the result in codeigniter nothing is returned:
$result = $this->db->query($query);
CI_DB_sqlsrv_result Object
(
[conn_id] => Resource id #30
[result_id] => Resource id #41
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] => -1
[row_data] =>
)
I have tried putting the query in a transaction but got the same result.
Any insight greatly appreciated.
Possible this be helpful for you -
;WITH [rows] AS
(
SELECT
a.[PatientID]
, a.[BGValue]
, a.[createdate]
, a.[HospitalUnit]
, Hospital = 'MSHA'
, h.[system_name]
, f.[facility_code]
, f.[facility_name]
, u.Treatment
, rn = ROW_NUMBER() OVER (ORDER BY u.[PatientID], u.[createdate])
FROM (
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'IV'
FROM dbo.MSHA_IVTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
UNION ALL
SELECT
PatientID
, BGValue
, createdate
, HospitalUnit
, Treatment = 'SubQ'
FROM dbo.MSHA_SubQTreatment
WHERE createdate BETWEEN '20130501' AND '20130531'
) a
JOIN [dbo].[MSHA_Patients] p ON p.[PatientID] = a.[PatientID]
JOIN [dbo].[Facilities] f ON f.[facility_code] = p.[facility_code]
JOIN [dbo].[Hospitals] h ON f.[Hospital] = h.[Hospital]
)
SELECT
mc.[PatientID]
, mc.[BGValue]
, mc.[createdate]
, mc.[Hospital]
, [System] = mc.[system_name]
, mc.[facility_code]
, mc.[facility_name]
, mc.[HospitalUnit]
, [Interval] = DATEDIFF(SECOND, mp.[createdate], mc.[createdate]) / 60
, mc.[Treatment]
FROM [rows] mc
JOIN [rows] mp ON mc.rn = mp.rn + 1 AND mc.[PatientID] = mp.[PatientID]
ORDER BY mc.[createdate];

Resources