SQL Server SELECT statement compare time in db with current time - sql-server-2008

This is probably a noob question, but i am a little stuck.
I have this long SELECT query :
SELECT
dbo.Dagplanning.GeldigOp ,
dbo.Trips_Bus.Route ,
dbo.Trips_Bus.TripStart AS BeginUur ,
dbo.Places.Naam AS BeginPlaats ,
dbo.Trips_Bus.TripEnd AS EindUur ,
dbo.Trips_Bus.Duty AS Dienst ,
dbo.Trips_Bus.Block ,
dbo.Personeel.Personeelsnummer ,
dbo.Personeel.Naam ,
dbo.Personeel.VoorNaam ,
dbo.Trips_Bus.OpDay ,
dbo.Trips_Bus.PeriodeID
FROM
dbo.Dagplanning ,
dbo.Personeel ,
dbo.Trips_Bus ,
dbo.Places
WHERE
dbo.Trips_Bus.TripStart >= DATEADD(minute, DATEDIFF(minute, -5, GETDATE()), 0)
AND dbo.Trips_Bus.TripStart <= DATEADD(minute, DATEDIFF(minute, 300, GETDATE()), 0)
AND dbo.Personeel.Personeelsnummer = dbo.Dagplanning.Personeelsnummer
AND dbo.Trips_Bus.Duty = ( dbo.Dagplanning.Rol + '+' + REPLICATE('0', 3 - LEN(dbo.Dagplanning.Dienst)) + dbo.Dagplanning.Dienst )
AND dbo.Trips_bus.Opday LIKE '%" + opdag + "%'
AND dbo.Trips_Bus.PeriodeID = '" + periodeid + "'
AND dbo.Dagplanning.GeldigOp = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
AND dbo.Trips_Bus.TripFrom = dbo.Places.Place
ORDER BY
dbo.Trips_Bus.TripStart ASC
It's actually this part that I have a problem with:
WHERE
dbo.Trips_Bus.TripStart >= DATEADD(minute, DATEDIFF(minute, -5, GETDATE()), 0)
AND dbo.Trips_Bus.TripStart <= DATEADD(minute, DATEDIFF(minute, 300, GETDATE()), 0)
This returns nothing, no error but also no data. De data in the table is stored like this example : 21:50:00
Any idea what I am doing wrong? Please be gentle ;-)
Oh, I am completely new at this, so please keep that in mind!

Related

Count/sum not working the way intended

I'm hoping this is just an error in my formatting so i won't post more of my query than necessary.
I had a large query with multiple joins and several SUM arguments (the point of this query is to aggregate daily totals every time it gets ran).
This is my trouble line:
sum(case when (duration > 60 and LEGTYPE1 = 1) then 1 else 0 end)
I also tried this:
count(case when (duration > 60 and LEGTYPE1 = 1) then 1 else null end)
Here's the problem: The sum case returns either a 1 or 0, and the count line does return the count (13,14,16) but it's not the right number for my records.
Here's the whole query for context:
SELECT c.extension
, sum(Duration) AS Total_Talk_Time_seconds
, round(sum(Duration) / 60,2) AS Total_Talk_Time_minutes
, sum(if(LEGTYPE1 = 1,1,0)) AS Total_Outbound
, sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Inbound
, sum(if(Answered = 1,0,1)) AS Total_Missed
, SUM(IF(LEGTYPE1 = 1, 1, 0)) + -- outbound calls
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) + -- inbound calls
SUM(IF(Answered = 1, 0, 1)) AS Total_Calls
, NOW() AS Time_of_report
, curdate() AS Date_of_report
FROM cdrdb.session a
INNER JOIN cdrdb.callsummary b
ON a.NOTABLECALLID = b.NOTABLECALLID
INNER join cdrdb.mxuser c
ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID
WHERE b.ts >= curdate()
AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312)
group by c.extension
SO, when I do the count version of that line, the number matches the total number of calls, where it should only represent the outbound ones that last longer than 60 seconds. The data is correct and the fields are correct, I'm simply asking if my syntax is correct or if there's simply a better way to structure it.
Not sure I follow your logic but:
sum(if(LEGTYPE1 = 2,1,0) and ANSWERED = 1) AS Total_Inbound
and
SUM(IF(LEGTYPE1 = 2, 1, 0) AND ANSWERED = 1) +
SUM(IF(Answered = 1, 0, 1)) AS Total_Calls
Seem wrong. Try:
sum(if(LEGTYPE1 = 2 and ANSWERED = 1, 1, 0) AS Total_Inbound
and
SUM(IF(LEGTYPE1 = 2 AND ANSWERED =1 , 1, 0) +
IF(Answered = 1, 0, 1)
) AS Total_Calls

Add grand total to totals in SQL

I have the bellow query and it works.
I just need to add a line at the bottom that gives the grand total
SELECT ItemType.Description,
SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item
on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType
on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving
on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description
Use CTE and UNION the rows with grand total row.
with CTE
(
SELECT ItemType.Description,
SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where
InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description
)
SELECT Description,TOTAL FROM CTE
UNION
SELECT 'GRAND TOTAL',SUM(TOTAL) FROM CTE
use your returned result as temp result
;WITH TEMP AS(
SELECT ItemType.Description, SUM(Price * Quantity)as 'TOTAL'
FROM [MIETRAK].[dbo].[PurchaseOrderReceivingLine]
join Item
on PurchaseOrderReceivingLine.ItemFK = item.ItemPK
join ItemType
on Item.ItemTypeFK = ItemType.ItemTypePK
join PurchaseOrderReceiving
on PurchaseOrderReceivingLine.PurchaseOrderReceivingFK = PurchaseOrderReceiving.PurchaseOrderReceivingPK
where InvoiceDate >= dateadd(wk, datediff(wk, 0, getdate()) - 1, 0)
and InvoiceDate < dateadd(wk, datediff(wk, 0, getdate()), 0)
group by ItemType.Description
)
SELECT * FROM TEMP
UNION
SELECT 'BIG SUM',SUM(TOTAL) TEMP

How to replace NULL with empty string in SQL?

I am using below query to fetch column value by comma separated.
(SELECT STUFF ((SELECT ',' + CAST(Proj_ID AS VARCHAR) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)
Can anyone guide me to replace null value by empty string here.
Updated:
(SELECT STUFF ((SELECT ',' + coalesce( CAST(Proj_ID AS VARCHAR), '' ) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)
Try IsNull
select ISNULL(Column,'') as ColumnName
OR COALESCE
select COALESCE(NULLIF(ColumnName,''), 'Column')
An example from the AdventureWorks database
select e.ModifiedDate, ISNULL(p.FirstName,'') as FirstName
from Person.BusinessEntity as e
left join Person.Person as p on e.BusinessEntityID = p.BusinessEntityID
By using this, if there are no matching Person records, the FirstName will be displayed as an empty string instead of NULL
You can white out null values with the coalesce function
select coalesce(MyColumn, '')
Coalesce takes any number of columns or constants and returns the first one which isn't null.
Your query would be:
(SELECT STUFF ((SELECT ',' + convert(varchar, coalesce( Proj_ID, '' )) FROM PROJECT
left join dbo.PROJ_STA on
Project.PROJ_STA_ID = Project.PROJ_STA_ID
WHERE ENTER_DT < DATEADD(Year, -7, GETDATE()) AND PROJ_LFCYC_STA_CD = 'A' AND
PROJ_STA.PROJ_STA_DS = 'Cancelled' FOR XML PATH('')), 1, 1, '')
AS Enter_Date)

Creating a calendar in sql

We use a lookup table in a database for grouping weeks, months and years. Sadly the chap who created it has long since gone and the calendar runs out at the end of the year! So I really need to find a way of adding to it! Its set up with the following columns:
I'm not very good in sql(MS2008) to be honest and ive stuggeled with it, we cant set anything new up as everything is built around this!
you can do smth like this, but I don't get why your calendar starts from March?
declare #Date_Start date, #Date_End date
select #Date_Start = '20130101'
select #Date_End = '20131231'
;with
CTE_Dates as (
select #Date_Start as [Date]
union all
select dateadd(dd, 1, [Date])
from CTE_Dates
where [Date] < #Date_End
),
CTE_Calendar as (
select
[Date],
datename(dw, [Date]) as [Day],
datepart(ww, [Date]) as [Week],
datepart(mm, [Date]) as [MonthID],
dateadd(mm, datediff(mm, 0, getdate()), 0) as [Month],
datepart(yy, [Date]) as [YearID],
dateadd(yy, datediff(yy, 0, getdate()), 0) as [Year],
datepart(qq, [Date]) as [QuarterID],
dateadd(qq, datediff(qq, 0, getdate()), 0) as [Quarter]
from CTE_Dates
)
select
row_number() over (order by [Date]) + #Start_ID - 1 as ID,
*
from CTE_Calendar
option (maxrecursion 0)
SQL FIDDLE EXAMPLE

Stored Procedure Throws Error, but running as a query does not

I am aggregating data for reporting, and have a stored procedure that I am trying to insert into a temporary table. If I just run EXEC <stored_proc_name> it works just fine. However, when I try and run the following code:
Create table #TempResults2
(
slscode varchar(3),
intakes_this_month int,
intakes_this_year int,
intakes_last_month int,
intakes_two_months int,
intakes_three_months int,
intakes_four_months int,
intakes_five_months int,
intakes_six_months int,
ships_this_month int,
ships_last_month int,
ships_two_months int,
ships_three_months int,
ships_four_months int,
ships_five_months int,
ships_six_months int,
ships_this_year int
PRIMARY KEY CLUSTERED (SLSCODE)
)
INSERT INTO #TempResults2
EXEC crm.dbo.sp_sales_info
SELECT * FROM #TempResults2
DROP TABLE #TempResults2
I get the following error:
Msg 8114, Level 16, State 1, Procedure sp_sales_info, Line 36
Error converting data type varchar to int.
Warning: Null value is eliminated by an aggregate or other SET operation.
Here is my stored procedure, and I know the problem is somewhere in the first section (where I get all the shipping information) because I can comment that out and just select the intake stuff and the temp table thing works:
UPDATE here is the full stored proc
ALTER PROCEDURE [dbo].[sp_sales_info]
-- Add the parameters for the stored procedure here
AS
BEGIN
DECLARE
#today date, #this_month date, #last_month_start date, #last_month_end date,
#two_months_start date, #two_months_end date, #three_months_start date, #three_months_end date,
#four_months_start date, #four_months_end date, #five_months_start date, #five_months_end date,
#six_months_start date, #six_months_end date, #this_year_start date, #startdate date, #enddate date;
SET #today = GETDATE();
SET #this_month = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0);
SET #last_month_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1, 0);
SET #last_month_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -1 + 1, 0));
SET #two_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2, 0);
SET #two_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -2 + 1, 0));
SET #three_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3, 0);
SET #three_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -3 + 1, 0));
SET #four_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4, 0);
SET #four_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -4 + 1, 0));
SET #five_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5, 0);
SET #five_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -5 + 1, 0));
SET #six_months_start = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6, 0);
SET #six_months_end = DATEADD(MILLISECOND, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + -6 + 1, 0));
SET #this_year_start = CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0) as DATE);
SET #startdate = DATEADD(YEAR, -1, GETDATE());
SET #enddate = #today;
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT
a.*,
d.intakes_this_month,
d.intakes_last_month,
d.intakes_two_months,
d.intakes_three_months,
d.intakes_four_months,
d.intakes_five_months,
d.intakes_six_months,
d.intakes_this_year
FROM
(
SELECT
sum(CASE WHEN a.SHIPDATE >= #this_month THEN 1 ELSE 0 END) AS ships_this_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS ships_last_month,
sum(CASE WHEN a.SHIPDATE BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS ships_two_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS ships_three_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS ships_four_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS ships_five_months,
sum(CASE WHEN a.SHIPDATE BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS ships_six_months,
sum(CASE WHEN a.SHIPDATE >= #this_year_start THEN 1 ELSE 0 END) AS ships_this_year,
b.slcode
FROM
(
SELECT
A.ACCOUNT AS CODE,
MIN(CAST(A.BILLDATETIME AS DATE)) AS SHIPDATE
FROM PACWARE.ADS.ARODME A
LEFT OUTER JOIN PACWARE.ADS.PTDME B ON A.PTCODE=B.CODE_
LEFT OUTER JOIN event.dbo.newdate() D ON A.ACCOUNT=D.ACCOUNT
LEFT OUTER JOIN event.dbo.newdate_extras() D2 ON A.ACCOUNT=D2.ACCOUNT
WHERE A.BILLDATETIME>=#startdate
AND A.BILLDATETIME<=#enddate
AND (
(D.NEWDATE>=#startdate AND D.NEWDATE<=#enddate) OR
(D2.NEWDATE IS NOT NULL AND D2.NEWDATE>=#startdate AND D2.NEWDATE<=#enddate) OR
B.MEDICAREID='L7900'
)
AND B.MEDICAREID IN ('A4253','L7900','A9276')
AND A.CATEGORY<>'ID'
Group by
A.ACCOUNT,
B.MEDICAREID,
A.CATEGORY
) a
JOIN event.dbo.patient_dg() b on a.CODE = b.code
GROUP BY b.slcode
) a
JOIN (
SELECT
sum(CASE WHEN a.regdate >= #this_month THEN 1 ELSE 0 END) AS intakes_this_month,
sum(CASE WHEN a.regdate BETWEEN #last_month_start AND #last_month_end THEN 1 ELSE 0 END) AS intakes_last_month,
sum(CASE WHEN a.regdate BETWEEN #two_months_start AND #two_months_end THEN 1 ELSE 0 END) AS intakes_two_months,
sum(CASE WHEN a.regdate BETWEEN #three_months_start AND #three_months_end THEN 1 ELSE 0 END) AS intakes_three_months,
sum(CASE WHEN a.regdate BETWEEN #four_months_start AND #four_months_end THEN 1 ELSE 0 END) AS intakes_four_months,
sum(CASE WHEN a.regdate BETWEEN #five_months_start AND #five_months_end THEN 1 ELSE 0 END) AS intakes_five_months,
sum(CASE WHEN a.regdate BETWEEN #six_months_start AND #six_months_end THEN 1 ELSE 0 END) AS intakes_six_months,
sum(CASE WHEN a.regdate >= #this_year_start THEN 1 ELSE 0 END) AS intakes_this_year,
a.slscode
FROM
event.dbo.patient_dg_lite() a
GROUP BY a.slscode
) d on a.slcode = d.slscode
JOIN event.dbo.employee_slscode b on a.slcode = b.slscode
JOIN event.dbo.employee c on b.employee_id = c.id
END
Your columns aren't in the same ordinal positions slscode is defined first in the CREATE TABLE.
Create table #TempResults2
(
slscode varchar(3),
/*Rest of table*/
ships_this_year int
)
But your SELECT in the stored procedure has it as the last column
SELECT
/* Loads of CASE statements*/
b.slcode
FROM /* ... */
So you are trying to insert the slscode varchar column into the integer ships_this_year column