SQL count date time - sql

I have to concatenate the date and time portion of two fields, which I have managed to do, then I need to test if the result is < getdate()
select count(cast(cast(DischargeDatenew as date) as datetime) + cast(DischargeTime as time))as Requiredby FROM [dbo].[Main]
where Location = 'Home' and ScriptTypeID = '1' and Requiredby < GETDATE()
Unfortunately the second Requiredby comes up as an invalid column name. How can I get this query to work? Do I need a subquery?

You don't need the calculation in COUNT, simply move it to WHERE:
select count(*)
FROM [dbo].[Main]
where Location = 'Home' and ScriptTypeID = '1'
and cast(cast(DischargeDatenew as date) as datetime)
+ cast(DischargeTime as time) < GETDATE()

Yes you will need subquery:
select * from (select someExpression as Requiredby
FROM [dbo].[Main]
where Location = 'Home' and ScriptTypeID = '1') t
where Requiredby < GETDATE()
But I really think you want this:
select sum(case when cast(cast(DischargeDatenew as date) as datetime) +
cast(DischargeTime as time) < getdate() then 1
else 0 end) as Requiredby
FROM [dbo].[Main]
where Location = 'Home' and ScriptTypeID = '1'

Related

Adding between dates - sql query

Currently I have a query that will get me the data from the pervious month .
I need to change thisso I can choose a selected date range that could allow me to input 2 dates and pull back all results between them.
See my query below:
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and month(I.Date_Key) = (select case when Month (GETDATE())-1 = 0 then 12 else Month (GETDATE())-1 end)
and year(I.Date_Key) = (select case when Month (GETDATE()) -1 = 0 then year (GETDATE()) -1 ELSE YEAR (GETDATE()) end)
I need to be able to say where dates between dd/mm/yy and dd/mm/yy
You could declare the dates a variables:
Declare #Startdate as datetime
Declare #Enddate as datetime
set #Startdate = '01-AUG-20'
set #Enddate = '22-OCT-20'
select * from Table1 I
inner join Service K on I.Service_Key = K.Service_Key
inner join Status S on I.Status_Key = S.Status_Key
where K.Service_Key = '1'
and S.Status_Name = 'Closed'
and I.Date_Key > #Startdate
and I.Date_Key < #Enddate
A simple method is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
datediff(month, i.Date_key, getdate()) = 1
That version, however, cannot use an index on i.Date_Key if that is appropriate. A more index friendly version is:
where K.Service_Key = '1' and
S.Status_Name = 'Closed' and
i.Date_key < datefromparts(year(getdate()), month(getdate()), 1) and
i.Date_key >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

SQL concat few select into one big table

I have table with data:
YYYY/MM/DD HH:MM:SS - Number of views, number of clicks, etc..
YYYY/MM/DD HH:MM:SS - ...
I want sum all those columns into sum value.
Like:
1. YYYY/MM/DD - sum of views, sum of clicks
What I have done:
1. Query foreach column.
For views;
select
cast([EventTime] as date) as 'Date',
Count([Id]) as 'Views'
from [TelemetryData]
where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and [EventName] = 'DiscountView'
group by cast([EventTime] as date)
order by cast([EventTime] as date) asc
Number of clicks per day:
select
cast([EventTime] as date) as 'Date',
Count([Id]) as 'Clicks'
from [TelemetryData]
where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and [EventName] = 'DiscountClick'
group by cast([EventTime] as date)
order by cast([EventTime] as date) asc
How I can sum all of them into one row per day?
Try it with checks and sums:
SELECT cast([EventTime] as date) as 'Date', SUM(case when [EventName]='DiscountClick' then 1 else 0 end) as 'Clicks', SUM(case when [EventName]='DiscountView' then 1 else 0 end) as 'Views'
from [TelemetryData]
where [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and ([EventName] = 'DiscountView' or [EventName] = 'DiscountClick')
group by cast([EventTime] as date)
order by cast([EventTime] as date) asc
What has been changed:
We first were maded where column to filter both Views and Clicks.
Then we used SUM but with CASE when EVENT=SOMETHING we are adding 1, otherwise 0.
With your group, you will get both by days at one query.
use SUM with CASE..
sum(case when [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and [EventName] = 'DiscountClick' then noofclicks column else 0 end
) as clicks
sum(case when [DiscountId] = '8773fd1b-f0c0-41fd-b0a0-ab8238f227f5'
and [EventName] = 'DiscountView' then view column else 0 end
) as views
and so on for other ....
from
table
group by cast([EventTime] as date)
order by cast([EventTime] as date)

Group by within Sub Query

Hi I have the code below which brings through a total by due and complete as well as the date. However I want to summarize by date, please can someone assist?
SELECT CONVERT(varchar(15), GRLastDt, 111) as Date_,
(
SELECT COUNT(*) AS Expr1
FROM dbo.AN_Admin_VendorReturns_090_Final
WHERE (Complete = 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
) AS Complete,
(
SELECT COUNT(*) AS Expr1
FROM dbo.AN_Admin_VendorReturns_090_Final AS AN_Admin_VendorReturns_090_Final_1
WHERE (Complete <> 'X') AND (CONVERT(varchar(15), GRLastDt, 111) >= GETDATE() - 60)
) AS DUE
FROM dbo.AN_Admin_VendorReturns_090_Final
group by CONVERT(varchar(15), GRLastDt, 111)
SELECT CGRLastDt as Date_,
SUM(CASE WHEN Complete = 'X' Then 1 Else 0 END) AS Complete,
SUM(CASE WHEN Complete <> 'X' Then 1 Else 0 END) AS Due
FROM dbo.AN_Admin_VendorReturns_090_Final
WHERE GRLastDt >= GETDATE() - 60
GROUP BY GRLastDt
Please note that I haven't validated this SQL for syntax and doing this in notepad.

confusion writing self join query

I have to write a SQL query and I am confused either I can solve it by self join or using an inner query.
I have a table containing columns
UserID, DateSubscription, Status
Status can be 'E' or 'R'.
I have to select users that has subscription Date between Date1 and Date2 and that UserID should not load who have Status = 'E' and is not in Date Range between Date1 And Date2.
UserID can exist in multiple rows with different status
Below is the query i tried
SELECT
IDNO,
IND_ID,
IND_SRC,
EXPIRY_DATE,
RECSTA
FROM
VIND,
VSCR
WHERE
VIND.IND_ID = VSCR.IND_ID
AND
VIND.IND_SRC = VSCR.IND_SRC
AND
EXPIRY_DATE >= '2015-04-25'
AND
EXPIRY_DATE <= '2015-06-25'
AND
(
RECSTA <> 'E'
AND
EXPIRY_DATE > '2015-06-25'
)
I'd use NOT EXISTSto check the second requirement
SELECT
UserID
FROM
Subscriptions
WHERE
DateSubscription BETWEEN #date1 and #date2
AND NOT EXISTS
(SELECT
NULL
FROM
Subscriptions OtherSubscriptions
WHERE
-- Get UserIDs other rows
Subscriptions.UserID = OtherSubscriptions.UserID
-- Only rows that have status 'E'
AND OtherSubscriptions.Status = 'E'
-- subscription is before #date1 or after #date2
AND (OtherSubscriptions.DateSubscription < #date1
OR OtherSubscriptions.DateSubscription > #date2)
One way to do this would be to group by on userid and filter the data using HAVING and CASE.
SELECT UserID, DateSubscription, Status
FROM UserStatusTable
GROUP BY UserID
HAVING SUM(CASE WHEN DateSubscription BETWEEN Date1 AND Date2 THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN DateSubscription NOT BETWEEN Date1 AND Date2 AND Status = 'E' THEN 1 ELSE 0 END) = 0
Try This.
select UserID, DateSubscription
from table
where DateSubscription between #startDate and #endDate and
(Status <> 'E' OR DateSubscription not between #startDate and #endDate)
If I understand correctly you want all records where the expiry date is between A and B, and also all records outside this date where the status is NOT E
select *
from yourtable
where EXPIRY_DATE between #startDateParam and #endDateParam
or [Status] <> 'E'

SQL Date Order Correction

Working on a SQL statement here and I have sort of a stupid question. Ive got this date field that spits out various dates from years and months etc. I'm trying to order them correctly but i get only the month in order. Example is:
01-05-2012
12-30-2011
12-18-2011
11-25-2011
11-24-2011
Etc.
My query is as follows:
SELECT TOP (100) PERCENT CONVERT(VARCHAR(10), A.tran_end_time, 110) AS Date
FROM dbo.ttdpur040101_CT AS A INNER JOIN
dbo.ttdpur040101_Audit AS B ON NOT (A.tran_begin_time > B.event_time_local OR
A.tran_end_time < B.event_time_local) AND (A.__$operation = 2 AND B.action_id = 'IN' OR
(A.__$operation = 3 OR
A.__$operation = 4) AND B.action_id = 'UP' OR
A.__$operation = 1 AND B.action_id = 'DL') AND B.class_type = 'U'
WHERE (B.server_principal_name = #Name)
GROUP BY CONVERT(VARCHAR(10), A.tran_end_time, 110)
ORDER BY Date
I would like to have it shown as follows:
11-24-2011
11-25-2011
12-18-2011
12-25-2011
01-08-2012
01-09-2012
etc.
Thanks
You are ordering by a Date column that has been converted to a VARCHAR(). Instead order by the original date column:
ORDER BY A.tran_end_time ASC
That's because Date is a varchar.
Try it this way:
SELECT TOP (100) PERCENT CONVERT(VARCHAR(10), A.tran_end_time, 110) AS Date
FROM dbo.ttdpur040101_CT AS A INNER JOIN
dbo.ttdpur040101_Audit AS B ON NOT (A.tran_begin_time > B.event_time_local OR
A.tran_end_time < B.event_time_local) AND (A.__$operation = 2 AND B.action_id = 'IN' OR
(A.__$operation = 3 OR
A.__$operation = 4) AND B.action_id = 'UP' OR
A.__$operation = 1 AND B.action_id = 'DL') AND B.class_type = 'U'
WHERE (B.server_principal_name = #Name)
GROUP BY CONVERT(VARCHAR(10), A.tran_end_time, 110)
ORDER BY CONVERT(DATETIME, Date, 103) ASC
SELECT CONVERT(VARCHAR(10), [Date], 110) FROM (
SELECT TOP (100) PERCENT DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0) AS Date
FROM dbo.ttdpur040101_CT AS A
INNER JOIN dbo.ttdpur040101_Audit AS B ON
NOT (A.tran_begin_time > B.event_time_local OR
A.tran_end_time < B.event_time_local) AND
(A.__$operation = 2 AND B.action_id = 'IN' OR
(A.__$operation = 3 OR A.__$operation = 4) AND
B.action_id = 'UP' OR
A.__$operation = 1 AND
B.action_id = 'DL'
) AND
B.class_type = 'U'
WHERE (B.server_principal_name = #Name)
GROUP BY DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0)
) t
ORDER BY [Date]
Quite important is "rounding" to date part only. Faster than converting to varchar is DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0) - because it's just math that SQL Server can do much faster than varchar manipulation.