Using DateDiff with GetDate() in tsql - tsql

I am trying to use GetDate inside a DateDiff along with a case statement. If field one is null I would like to use the current date. This is the code I am working with:
DateDiff(DAY, (Select Min(case when (demand_labor.arrive_dt is null)
then GETDATE()
else (demand_labor.arrive_dt)
end)
From demand Inner Join demand_labor On demand.demand_id =
demand_labor.demand_id
Where (order_line.order_id = demand.order_id)),
c_service_call_env.resolve_date) As A2R2,
For one reason or another though when it is null it is not setting the date, the field stays null. Any help would be greatly appreciated.

ISNULL ( demand_labor.arrive_dt , GETDATE() )
ISNULL
DateDiff is supposed to have 3 components
Not sure what you are trying to do there
DateDiff(DAY, ISNULL ( demand_labor.arrive_dt , GETDATE() ), open_dt)

I am trying to do a dateDiff with the .arrive_dt and open_dt. That
being said though if the .arrive_dt is null I would like to check the
dateDiff between the current date and the open_dt. There also could be
more then one .arrive_dt that is why I am selecting the min
a case statement should work
case when .arrive_dt is null then datediff(day, getdate(), Open_dt )
else datediff(day, min(.arrive_dt), open_dt) end
group by *as needed*
switch the order within the datediffs as needed
http://sqlfiddle.com/#!3/9b6c5/1/0

Related

SQL Server and index and null parameters

I have the below stored procedure that run against 2,304,697 records :
#startdate DATETIME NULL,
#enddate DATETIME NULL,
#drilldown VARCHAR(20) NULL
AS
BEGIN
SELECT
DATENAME(YEAR, ReceivingTime) as Year,
MAX(DATENAME(MONTH, ReceivingTime)) AS Month,
ProductionLocation,
CAST(COUNT(*) * 100.0 / SUM(COUNT(*) * 100) OVER (PARTITION BY DATENAME(YEAR, ReceivingTime), MONTH(ReceivingTime)) AS DECIMAL(10,2)) AS TotalsByMonth,
CAST(COUNT(*) * 100.0 / SUM(COUNT(*) * 100) OVER (PARTITION BY DATENAME(YEAR, ReceivingTime)) AS DECIMAL(10, 2)) AS TotalsByYear
FROM
Jobs_analytics
WHERE
ProductionLocation IS NOT NULL
AND ((ReceivingTime BETWEEN dbo.cleanStartDate(#startdate) AND dbo.cleanEndDate(#enddate))
AND #startdate IS NULL)
OR ((YEAR(ReceivingTime) = #drilldown) AND #drilldown IS NULL)
GROUP BY
DATENAME(YEAR, ReceivingTime),
DATEPART(MONTH, ReceivingTime), ProductionLocation
ORDER BY
DATENAME(YEAR, ReceivingTime),
DATEPART(MONTH, ReceivingTime)
The query works well in that it returns a data set in about 8 seconds. But I like to get the speed better So I added the below index:
CREATE INDEX RecDateTime
ON Jobs_analytics(RecDateTime, ProductionLocation)
go
however that really didn't improve anything. So I ran the execution plan and I notice that the my index is being used and the cost was 35% and my sort was at 6%.
So I reworked my where clause from this:
WHERE ProductionLocation IS NOT NULL AND
((ReceivingTime BETWEEN dbo.cleanStartDate(#startdate) and dbo.cleanEndDate(#enddate) ) AND #drilldown IS NULL)
OR ((YEAR(ReceivingTime) = #drilldown) AND #startdate IS NULL)
to this:
WHERE ProductionLocation IS NOT NULL AND
ReceivingTime BETWEEN dbo.cleanStartDate('2018-07-01') and dbo.cleanEndDate('2019-08-25')
and I got the query to run in a second. As you can see there is no more filter and the cost on the cluster is at 3%..( something I did not realize)
The NULL parameter checks are for a report that sometimes will have null values set. so I don't have to maintain two stored procedures. I can write a second stored procedure and just remove the where clause items but I rather not. is there any index or changes to my query that anyone could suggest that might help
Thanks
Mike
Okay if anyone comes across this this is what I found out:
I was testing the wrong parameter for null values within the OR
clause.
I have function that adds the hh:mm:ss to a date that was also
causing me problem.
I fixed both those items and the query runs in about a second.

T-SQL Union returns duplicated row (date)

I was trying to solve the issue of returning sum for each date in a specific date range, no matter if data is present for a day or not.
I have found that the best way would be to use a table pre-populated with all dates, select date range and union it with my data.
For some reason couldn't get left join to work, but union looks like working almost perfectly. The only issue is that it returns duplicates for dates where data is present in my data table.
SELECT NULL AS Visitors
,D.DATE AS Day
FROM Database.support.dates D
WHERE D.DATE BETWEEN #Start_date
AND #End_date
UNION
SELECT count(V.id) AS Visitors
,DATEADD(day, 0, DATEDIFF(day, 0, V.CreateTime)) AS Day
FROM Database.Clients.Clients V
WHERE V.CreateTime BETWEEN #Start_date
AND #End_date
AND V.WADID = #WADID
AND (
V.WAPID = #WAPID
OR #WAPID IS NULL
)
GROUP BY DATEADD(day, 0, DATEDIFF(day, 0, V.CreateTime))
ORDER BY Day DESC
Was researching it whole last day and still can't get it working :/
I think that left joining your calendar table to your current query actually was the right thing to do. That being said, you can remedy your current situation by simply aggregating on the day, e.g. using MAX. By default, NULL values for each day would be ignored, so long as there is a non null visitor count present:
WITH cte AS (
SELECT NULL AS Visitors, D.DATE AS Day
FROM Database.support.dates D
WHERE D.DATE BETWEEN #Start_date AND #End_date
UNION
SELECT COUNT(V.id), DATEADD(day, 0, DATEDIFF(day, 0, V.CreateTime))
FROM Database.Clients.Clients V
WHERE V.CreateTime BETWEEN #Start_date AND #End_date AND
V.WADID = #WADID AND (V.WAPID = #WAPID OR #WAPID IS NULL)
GROUP BY DATEADD(day, 0, DATEDIFF(day, 0, V.CreateTime))
)
SELECT Day, MAX(Visitors) AS Visitors -- filter off unwanted NULL values
FROM cte
GROUP BY Day
ORDER BY Day DESC;

TSQL - Control a number sequence

Im a new in TSQL.
I have a table with a field called ODOMETER of a vehicle. I have to get the quantity of km in a period of time from 1st of the month to the end.
SELECT MAX(Odometer) - MIN(Odometer) as TotalKm FROM Table
This will work in ideal test scenary, but the Odomometer can be reset to 0 in anytime.
Someone can help to solve my problem, thank you.
I'm working with MS SQL 2012
EXAMPLE of records:
Date Odometer value
datetime var, 37210
datetime var, 37340
datetime var, 0
datetime var, 220
Try something like this using the LAG. There are other ways, but this should be easy.
EDIT: Changing the sample data to include records outside of the desired month range. Also simplifying that Reading for easy hand calc. Will shows a second option as siggested by OP.
DECLARE #tbl TABLE (stamp DATETIME, Reading INT)
INSERT INTO #tbl VALUES
('02/28/2014',0)
,('03/01/2014',10)
,('03/10/2014',20)
,('03/22/2014',0)
,('03/30/2014',10)
,('03/31/2014',20)
,('04/01/2014',30)
--Original solution with WHERE on the "outer" SELECT.
--This give a result of 40 as it include the change of 10 between 2/28 and 3/31.
;WITH cte AS (
SELECT Reading
,LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) LastReading
,Reading - LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) ChangeSinceLastReading
,CONVERT(date, stamp) stamp
FROM #tbl
)
SELECT SUM(CASE WHEN Reading = 0 THEN 0 ELSE ChangeSinceLastReading END)
FROM cte
WHERE stamp BETWEEN '03/01/2014' AND '03/31/2014'
--Second option with WHERE on the "inner" SELECT (within the CTE)
--This give a result of 30 as it include the change of 10 between 2/28 and 3/31 is by the filtered lag.
;WITH cte AS (
SELECT Reading
,LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) LastReading
,Reading - LAG(Reading,1,Reading) OVER (ORDER BY stamp ASC) ChangeSinceLastReading
,CONVERT(date, stamp) stamp
FROM #tbl
WHERE stamp BETWEEN '03/01/2014' AND '03/31/2014'
)
SELECT SUM(CASE WHEN Reading = 0 THEN 0 ELSE ChangeSinceLastReading END)
FROM cte
I think Karl solution using LAG is better than mine, but anyway:
;WITH [Rows] AS
(
SELECT o1.[Date], o1.[Value] as CurrentValue,
(SELECT TOP 1 o2.[Value]
FROM #tbl o2 WHERE o1.[Date] < o2.[Date]) as NextValue
FROM #tbl o1
)
SELECT SUM (CASE WHEN [NextValue] IS NULL OR [NextValue] < [CurrentValue] THEN 0 ELSE [NextValue] - [CurrentValue] END )
FROM [Rows]

counting all occurrences in the last year

I have a question, although I can't really go into specifics.
Will the following query:
SELECT DISTINCT tableOuter.Property, (SELECT COUNT(ID) FROM table AS tableInner WHERE tableInner.Property = tableOuter.Property)
FROM table AS tableOuter
WHERE tableOuter.DateTime > DATEADD(year, -1, GETDATE())
AND tableOuter.Property IN (
...
)
Select one instance of each property in the IN clause, together with how often a row with that property occured in the last year?
I just read up on Correlated Subqueries on MSDN, but am not sure if I got it right.
If i understand you corrrecly, you want to get all occurences of each Property in the last year, am i right?
Then use GROUP BY with a HAVING clause:
SELECT tableOuter.Property, COUNT(*) AS Count
FROM table AS tableOuter
GROUP BY tableOuter.Property
HAVING tableOuter.DateTime > DATEADD(year, -1, GETDATE())
AND tableOuter.Property IN ( .... )

Two questions about my SQL script. How to add subtotal/total lines, and a sorting issue

I have some T-SQL that generates a nice report giving a summary some stuff by month.
I have 2 questions, is there a way to get the to sort the months by calendar order, not by alpha? And, what i would like to do is add a total line for each year, and a total line for the whole report?
SELECT
CASE WHEN tmpActivity.Year IS NULL THEN
CASE WHEN tmpCreated.Year IS NULL THEN
CASE WHEN tmpContactsCreated.Year IS NULL THEN
null
ELSE tmpContactsCreated.Year END
ELSE tmpCreated.Year END
ELSE tmpActivity.Year END As Year,
CASE WHEN tmpActivity.Month IS NULL THEN
CASE WHEN tmpCreated.Month IS NULL THEN
CASE WHEN tmpContactsCreated.Month IS NULL THEN
null
ELSE DateName(month, DateAdd(month, tmpContactsCreated.Month - 1, '1900-01-01' )) END
ELSE DateName(month, DateAdd(month, tmpCreated.Month - 1, '1900-01-01' )) END
ELSE DateName(month, DateAdd(month, tmpActivity.Month - 1, '1900-01-01' )) END As Month,
CASE WHEN tmpActivity.ActiveAccounts IS NULL THEN 0 ELSE tmpActivity.ActiveAccounts END AS ActiveAccounts,
CASE WHEN tmpCreated.NewAccounts IS NULL THEN 0 ELSE tmpCreated.NewAccounts END AS NewAccounts,
CASE WHEN tmpContactsCreated.NewContacts IS NULL THEN 0 ELSE tmpContactsCreated.NewContacts END AS NewContacts
FROM
(
SELECT YEAR(LastLogon) As Year, MONTH(LastLogon) As Month, COUNT(*) As ActiveAccounts
FROM Users
WHERE LastLogon >= '1/1/1800'
GROUP BY YEAR(LastLogon), MONTH(LastLogon)
) as tmpActivity
FULL JOIN
(
SELECT YEAR(Created) As Year, MONTH(Created) As Month, COUNT(*) As NewAccounts
FROM Users
WHERE Created >= '1/1/1800'
GROUP BY YEAR(Created), MONTH(Created)
) as tmpCreated ON tmpCreated.Year = tmpActivity.Year AND tmpCreated.Month = tmpActivity.Month
FULL JOIN
(
SELECT YEAR(Created) As Year, MONTH(Created) As Month, COUNT(*) As NewContacts
FROM Contacts
WHERE Created >= '1/1/1800'
GROUP BY YEAR(Created), MONTH(Created)
) as tmpContactsCreated ON tmpContactsCreated.Year = tmpCreated.Year AND tmpContactsCreated.Month = tmpCreated.Month
Order By Year DESC, Month DESC
To order by the month use the following:
ORDER BY DATEPART(Month,Created) ASC
DatePart() returns an integer for the part specified 1 for January, 2 for Febuary etc.
You're SQL could be helped with the COALESCE() and ISNULL() functions. This is the same as your first select:
SELECT
COALESCE(tmpActivity.Year,tmpCreated.Year,tmpContactsCreated.Year) as Year,
COALESCE(tmpActivity.Month,tmpCreated.Month,tmpContactsCreated.Month) as Month,
ISNULL(tmpActivity.ActiveAccounts,0) AS ActiveAccounts,
ISNULL(tmpCreated.NewAccounts,0) AS NewAccounts,
ISNULL(tmpContactsCreated.NewContacts,0) AS NewContacts
I think there is a bug in your select, I believe your last line has to be this:
) as tmpContactsCreated ON (tmpContactsCreated.Year = tmpCreated.Year AND tmpContactsCreated.Month = tmpCreated.Month) OR
(tmpContactsCreated.Year = tmpActivity.Year AND tmpContactsCreated.Month = tmpActivity.Month)
But I would have to test this to be sure.
Adding in rollups is hard to do -- typically this is done externally to the SQL in the control or whatever displays the results. You could do something like this (contrived example):
SELECT 1 as reportOrder, date, amount, null as total
FROM invoices
UNION ALL
SELECT 2 , null, null, sum(amount)
FROM invoices
ORDER BY reportOrder, date
or you could not have the "extra" total column and put it in the amount column.