Find the latest entry amongst same number with a Dash? - sql-server

We have a table that stores a list of all the quotes we have sent out.
Anytime a customer revises the quotes, the system automatically appends a -1 or -2 based on last used number.
As an example
Original Quote Number : 24545
Customer asked for a revision, the quote number is now 24545-1, after sending the quote, we now have a revision again and the Quote is 24545-2 and so on.
I want to run a SQL query that will show them their Top 20 Quotes and incase of revisions, it should show the latest revisions.
Can you please help me?
I have already written a Query that would bring me top 20 quotes for the last 10 days.
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [Enterprise32].[dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() AND SalesRepCode = $id And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC

This makes some assumptions, but I think this might work. If not, sample data and expected result will be invaluable:
USE Enterprise32;
GO
WITH CTE AS(
SELECT V.EstimateNumber,
V.RevisionNumber,
TN1.CustName,
TN1.JobDescription,
TN1.TotalSellPrice,
TN1.EstimateStatus,
TN1.EstimateDate,
TN1.CommissionTableA,
ROW_NUMBER() OVER (PARTITION BY V.EstimateNumber ORDER BY V.RevisionNumber DESC) AS RN
FROM dbo.TableName1 TN1
CROSS APPLY (VALUES(NULLIF(CHARINDEX('-',TN1.EstimateNumber),0)))CI(I)
CROSS APPLY (VALUES(TRY_CONVERT(int,LEFT(TN1.EstimateNumber,ISNULL(CI.I,LEN(TN1.EstimateNumber))-1)),ISNULL(TRY_CONVERT(int,STUFF(TN1.EstimateNumber,1,CI.I,'')),0)))V(EstimateNumber,RevisionNumber)
WHERE TN1.EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE()
AND TN1.SalesRepCode = $id
And TN1.TotalSellPrice > '5000'
AND TN1.EstimateStatus = 'P')
SELECT TOP (20)
EstimateNumber,
RevisionNumber,
CustName,
JobDescription,
TotalSellPrice,
EstimateStatus,
EstimateDate,
CommissionTableA
FROM CTE
WHERE RN = 1;

With some minor changes, it might work, As there is no data sample:
SELECT Top 20
EstimateNumber,CustName,JobDescription,TotalSellPrice,EstimateStatus,EstimateDate,CommissionTableA
FROM [dbo].[tablename1] tt
LEFT JOIN
(
--Top 20 quotes Last EstimateNumber with revision
SELECT T20.RevisionFree_EstimateNumber +
CONVERT(VARCHAR,
MAX(CONVERT(INT,
SUBSTRING(t.EstimateNumber, CHARINDEX('-', EstimateNumber)+1, LEN(EstimateNumber)-CHARINDEX('-', EstimateNumber))))) Last_EstimateNumber
FROM
(
--Top 20 quotes Original EstimateNumber
SELECT DISTINCT Top 20
TotalSellPrice
,SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
where EstimateDate BETWEEN DATEADD(Day, -10, getdate()) AND GETDATE() And TotalSellPrice > '5000' AND EstimateStatus = 'P'
Order By TotalSellPrice DESC
)AS T20
LEFT JOIN
(
SELECT *, SUBSTRING(EstimateNumber, 1, CHARINDEX('-', EstimateNumber)) RevisionFree_EstimateNumber
FROM [dbo].[tablename1]
) t
ON T20.RevisionFree_EstimateNumber = t.RevisionFree_EstimateNumber
GROUP BY T20.RevisionFree_EstimateNumber
)LastEN
ON tt.EstimateNumber = LastEN.Last_EstimateNumber

Related

My SQL query runs perfectly, but when I add the CTE function, I get an error

My SQL query runs perfectly, but when I add the CTE function, I get an error
Please check this code and let me know what's wrong with the CTE:
WITH Consumption_details(UnitId, consumption, monthof, yearof) AS
(
SELECT
UnitId, SUM(consumption) AS consumption,
monthof, yearof
FROM
(SELECT
UnitId, apartment_consumption,
DATEPART(MONTH, day) AS monthof,
DATEPART(YEAR,day) AS yearof
FROM
MeterReading) AS t
GROUP BY
yearof, monthof, UnitId
HAVING
monthof = 2 AND yearof = 2022
ORDER BY
UnitID
)
You can't have ORDER BY inside the CTE (unless you also include TOP, which you shouldn't do in this case), and you need to do something with the CTE - it's just an expression, not a query on its own.
;;;/*be safe!*/;;;With cd(SonnenUnitId, consumption, monthof, yearof) AS
(
SELECT SonnenUnitId, ...
...
GROUP BY yearof, monthof, SonnenUnitId
HAVING monthof =2 and yearof =2022
)
SELECT * FROM cd Order by SonnenUnitID;
As an aside, this query could be a whole lot more efficient with no need for a CTE and a subquery, any of the HAVING, and the scan potentially becoming a seek.
DECLARE #mo int = 2, #yo int = 2022;
DECLARE #m date = DATEFROMPARTS(#yo, #mo, 1);
SELECT SonnenUnitId,
SUM(apartment_consumption) AS consumption,
monthof = #mo,
yearof = #yo
FROM dbo.SonnenMeterReading
WHERE [day] >= #m
AND [day] < DATEADD(MONTH, 1, #m)
GROUP BY SonnenUnitId
ORDER BY SonnenUnitId;

Display of online users on the system

I don't know exactly where I'm wrong, but I need a list of all the workers who are currently at work (for the current day), this is my sql query:
SELECT
zp.ID,
zp.USER_ID,
zp.Arrive,
zp.Deppart,
zp.DATUM
FROM time_recording as zp
INNER JOIN personal AS a on zp.USER_ID, = zp.USER_ID,
WHERE zp.Arrive IS NOT NULL
AND zp.Deppart IS NULL
AND zp.DATUM = convert(date, getdate())
ORDER BY zp.ID DESC
this is what the data looks like with my query:
For me the question is, how can I correct my query so that I only get the last Arrive time for the current day for each user?
In this case to get only these values:
Try this below script using ROW_NUMBER as below-
SELECT * FROM
(
SELECT zp.ID, zp.USER_ID, zp.Arrive, zp.Deppart, zp.DATUM,
ROW_NMBER() OVER(PARTITION BY zp.User_id ORDER BY zp.Arrive DESC) RN
FROM time_recording as zp
INNER JOIN personal AS a
on zp.USER_ID = zp.USER_ID
-- You need to adjust above join relation as both goes to same table
-- In addition, as you are selecting nothing from table personal, you can drop the total JOIN part
WHERE zp.Arrive IS NOT NULL
AND zp.Deppart IS NULL
AND zp.DATUM = convert(date, getdate())
)A
WHERE RN =1
you can try this:
SELECT DISTINCT
USER_ID,
LAR.LastArrive
FROM time_recording as tr
CROSS APPLY (
SELECT
MAX(Arrive) as LastArrive
FROM time_recording as ta
WHERE
tr.USER_ID = ta.USER_ID AND
ta.Arrive IS NOT NULL
) as LAR

Calculate the datediff() between the date 1 and 2

I need to calculate the datediff from one column where the in time marked with a 1 and the out time marked with a 2. if an employee swiped in and there is no out or out but there was no in i would like it to show as null.
I am not sure how I go about doing this.
SELECT
u.userid
,et.name
,CASE
WHEN scs.FullName is NULL THEN u.name
WHEN scs.FullName is NOT NULL THEN scs.FullName
END AS name
,e.LoggedTime AS SwipeTime
,CASE
WHEN et.name = 'Output On By Door' OR et.name = 'User Granted
Entry To Door Using Reading Device' THEN 1
ELSE 2
END AS SwipeTimeDiff
,d.name AS Door
FROM [Users] AS u
LEFT JOIN [Events] AS e ON e.RecordIndex1=u.UserID
LEFT JOIN [EventTypes] AS et on e.EventTypeID = et.EventTypeID
join .[Doors] AS d ON e.RecordIndex2 = d.DoorID
LEFT join SecurityContractorSignIn as scs on scs.Badge = u.lastname
WHERE LoggedTime > CONVERT(DATE, GETDATE()) and d.doorid in (32, 50, 42, 51, 33)
ORDER BY u.name,e.LoggedTime DESC
I would like to have a computed column with the time difference in days, hours and minutes or null if if there is a missing in(1) or out(2) time.
Well, the DATEDIFF() function is fully explained here and the difference for the specific datepart you want to extract is returned as an integer.
According to your need you may do something like but you will have the information in three (or more - if you want to extend) different columns:
-- Calculate the difference of how many days have passed
SELECT DATEDIFF(DAY, LoginTime, LogoutTime) AS DaysPassed
-- Calculate the difference of how many hours have passed
SELECT DATEDIFF(HOUR, LoginTime, LogoutTime) AS HoursPassed
-- Calculate the difference of how minutes have passed
SELECT DATEDIFF(MINUTE, LoginTime, LogoutTime) AS MinutesPassed
If you want to return a string whether the employee logged out or not you may use something like:
SELECT ISNULL(CONVERT(nvarchar(50), DATEDIFF(MONTH, '2019-01-04', NULL)), 'No logout')

Run t-sql script into ssrs 2012 with date parameter and select from (select) query

I want to report a script which contains a Select from(Select) , when I just run the second Select I have no problem but When I put the hole script it loads and nothing happen.
Here's my code :
SELECT top 100 *,
CASE
WHEN Frequency='1'
AND DATEDIFF(HOUR, T.MeasurementDate, T.nextMeasurement) > 1 THEN 'Missing Hour(s)'
WHEN Frequency='1'
AND T.MeasurementDate = T.maxMeasurement
AND DATEDIFF(HOUR, T.maxMeasurement, CONVERT(DATE, #EndDate)) > 1 THEN 'Missing Max Hour(s)'
WHEN Frequency='2'
AND DATEDIFF(DAY, T.MeasurementDate, T.nextMeasurement) > 1 THEN 'Missing Day(s)'
WHEN Frequency='2'
AND T.MeasurementDate = T.maxMeasurement
AND DATEDIFF(DAY, T.maxMeasurement, CONVERT(DATE, #EndDate)) > 1 THEN 'Missing Max Day(s)'
ELSE 'OK'
END AS [Verification] INTO #tt FROM
(SELECT top 100 Flow.Id AS idFlow, Flow.ComponentId, Flow.Frequency, pip.Name AS PipelineName, LEAD(Flow.MeasurementDate) OVER (Partition BY ComponentId, NominationCycle, LocationType, Frequency, FlowTypeId, UnitofMeasurement
ORDER BY MeasurementDate) nextMeasurement, MAX(Flow.MeasurementDate) OVER (PARTITION BY ComponentId, NominationCycle, LocationType, Frequency, FlowTypeId, UnitofMeasurement) maxMeasurement
FROM BentekDatabase.dbo.Flow Flow
INNER JOIN BentekDatabase.dbo.Pipeline pip ON Flow.PipelineId = pip.id
WHERE ScheduledVolume IS NOT NULL
AND MeasurementDate BETWEEN #StartDate AND #EndDate) AS T
SELECT COUNT (*)
FROM #tt
WHERE Verification != 'OK'
PS : The code run perfectly in SSMs when I declare values for 2 parameter.
I want to display the result of the last query ( select count (*) from #tt where Verification != 'OK') in a new page report results, which will contain the result of all my other queries too.
ANy Idea ?

SQL Query ; I want to get Enquiry_No which has not been updated since last 7 days

I am having two tables TblEnquiry with Enquiry _No as Primary Key and tblHistory for maintaing updatiing details with Enquiry_No as foreign key and History_CreatedOn field for date.
I want to get Enquiries which have not been updated since last 7 days.
SELECT e.*
FROM tblEnquiry e
WHERE NOT EXISTS(SELECT * FROM tblHistory h WHERE e.Enquiry_No = e.Enquiry_No AND h.History_CreatedOn >= DATEADD(dd, -7, GETDATE())
If you're using SQL Server:
SELECT
<add columns here>
FROM
tblEnquiry
WHERE
NOT EXISTS
(
SELECT *
FROM tblHistory H
WHERE H.enquiry_no = E.enquiry_no
AND H.history_createdon BETWEEN DATEADD(dy, -7, GETDATE()) AND GETDATE()
)
WITH Hist(enquiry_no, history_createdon) AS
(
SELECT Enquiry_No, History_CreatedOn
FROM tblHistory
WHERE History_CreatedOn >= DATEADD(dd, -7, GETDATE())
)
SELECT *
FROM tblEnquiry
LEFT OUTER JOIN Hist ON tblHist.enquiry_no = tblEnquiry.enquiry_no
WHERE tblHistory.enquiry_no IS NULL
This will avoid the poor performance of the standard NOT EXISTS query
Got the answer
select h1.Enquiry_No
from tblHistory h1
group by h1.Enquiry_No
having DATEDIFF(DD,Max(h1.History_CreatedOn),GETDATE())>=7
I got the Enquiries that have not been updated since last 7 days

Resources