In between dates issue - tsql

I have the following query:
SELECT QuoteReference, CreatedDate, StartDate, EndDate, Operation, OccurredAt, PerformedBy, FieldName, OldValue, NewValue
FROM Quotes, Audit
WHERE Quotes.ID = Audit.RowId
AND PaymentReference is not null
AND Audit.OccurredAt > Quotes.CompletedDate
AND Quotes.CreatedDate between '2010-04-01 11:00:00.027' AND '2010-07-30 11:39:22.027'
and TableName = 'QUOTE' OR TableName = 'Quotes'
ORDER BY Audit.OccurredAt desc
Despite trying a number of things, on the "quotes.createddate between..." line, I can't filter the resultset to include records with a create date between those times (1st april 2010 to 30th July 2012). How can I do this?

Your date range is incorrect, use:
between '2010-04-01 00:00:00:000' AND '2012-07-30 23:59:59:999'

Use ISO DATETIME FORMAT (yyyymmdd or yyyy-mm-ddThh:mi:ss.mmm) to sort the date formatting issue if any. Also try to USE JOIN tables instead of WHERE table1, table2,..
If other conditions are okay, following query should bring the records.
SELECT QuoteReference, CreatedDate, StartDate, EndDate, Operation,
OccurredAt, PerformedBy, FieldName, OldValue, NewValue
FROM Quotes JOIN Audit ON Quotes.ID = Audit.RowId --JOIN TABLES
WHERE PaymentReference is not null
AND Audit.OccurredAt > Quotes.CompletedDate
AND Quotes.CreatedDate
BETWEEN '20100401' AND '20100730' --Time ignored purposely for checking
AND TableName IN ('Quote','Quotes')
ORDER BY Audit.OccurredAt desc

Related

T-SQL apply where clause to function fields not working

I'm having a hard time filtering this view by CreateDate. The CreateDate in the table is in the following format: 2013-10-14 15:53:33.900
I managed to DATEPART the year month and day into separate columns, but now it's not letting me use my WHERE clause on those newly created columns. Specifically, the error is "Invalid Column Name CreateYear" for both lines. What am I doing wrong here guys? Is there a better/easier way to do this than parse out the day, month, and year? It seems overkill. I've spent quite a bit of hours on this to no avail.
SELECT convert(varchar, DATEPART(month,v.CreateDate)) CreateMonth,
convert(varchar, DATEPART(DAY,v.CreateDate)) CreateDay,
convert(varchar, DATEPART(YEAR,v.CreateDate)) CreateYear,
v.CreateDate,
v.customerName
From
vw_Name_SQL_DailyPartsUsage v
full outer join
ABC.serviceteamstechnicians t on v.TechnicianNumber = t.AgentNumber
full outer join
ABC.ServiceTeams s on t.STID = s.STID
where
CreateYear >= '02/01/2018'
and
CreateYear <= '02/20/2018'
You cannot reference an alias from the select in the where
Even if you could why would you expect year to be '02/01/2018'
Why are you converting to varchar
where year(v.CreateDate) = 2018
or
select crdate, cast(crdate as date), year(crdate), month(crdate), day(crdate)
from sysObjects
where cast(crdate as date) <= '2014-2-20'
and cast(crdate as date) >= '2000-2-10'
order by crdate
You could use:
SELECT convert(varchar, DATEPART(month,v.CreateDate)) CreateMonth,
convert(varchar, DATEPART(DAY,v.CreateDate)) CreateDay,
convert(varchar, DATEPART(YEAR,v.CreateDate)) CreateYear,
v.CreateDate,
v.customerName
From vw_Name_SQL_DailyPartsUsage v
full outer join
ABC.serviceteamstechnicians t on v.TechnicianNumber = t.AgentNumber
full outer join
ABC.ServiceTeams s on t.STID = s.STID
where CreateDate BETWEEN '20180102' and '20180220';
More info about the logical query processing is that you cannot refer to a column alias at SELECT in the WHERE clause without using a subquery/CROSS APPLY.

Google BigQuery: Select and group by "yyyy-mm" from date field ("yyyy-mm-dd") or timestamp

I would like to group by "yyyy-mm" from a date field ("yyyy-mm-dd") or timestamp field so that I can pull and group transactional data over multiple years without having to pull separate queries grouping by month for each year.
SELECT
CONCAT(STRING(YEAR(timestamp)),'-',RIGHT(STRING(100 + MONTH(timestamp)), 2)) AS yyyymm,
<any aggregations here>
FROM YourTable
GROUP BY 1
another option:
SELECT
STRFTIME_UTC_USEC(timestamp, "%Y-%m") AS yyyymm,
<any aggregations here>
FROM YourTable
GROUP BY 1
both versions should work with timestamp or date
You can use the following for Standard SQL:
SELECT concat(cast(format_date("%E4Y", cast(current_date() as date)) as string),'-',cast(format_date("%m", cast(current_date() as date)) as string)) as yyyymm, <other aggregations>
FROM <YourTable>
GROUP BY 1;
Just replace the current_date() with your column name containing the timestamp.

Filtering date does not return correct data

I have the following query.
SELECT *
FROM (SELECT temp.*, ROWNUM AS rn
FROM ( SELECT (id) M_ID,
CREATION_DATE,
RECIPIENT_STATUS,
PARENT_OR_CHILD,
CHILD_COUNT,
IS_PICKABLE,
IS_GOLDEN,
trxn_id,
id AS id,
MASTER_ID,
request_wf_state,
TITLE,
FIRST_NAME,
MIDDLE,
LAST_NAME,
FULL_NAME_LNF,
FULL_NAME_FNF,
NAME_OF_ORGANIZATION,
ADDRESS,
CITY,
STATE,
COUNTRY,
HCP_TYPE,
HCP_SUBTYPE,
is_edit_locked,
record_type rec_type,
DATA_SOURCE_NAME,
DEA_DATA,
NPI_DATA,
STATE_DATA,
RPPS,
SIREN_NUMBER,
FINESS,
ROW_NUMBER ()
OVER (PARTITION BY id ORDER BY full_name_fnf)
AS rp
FROM V_RECIPIENT_TRANS_SCRN_OP
WHERE 1 = 1
AND creation_date >=
to_date( '01-Sep-2015', 'DD-MON-YYYY') AND creation_date <=
to_date( '09-Sep-2015', 'DD-MON-YYYY')
ORDER BY CREATION_DATE DESC) temp
WHERE rp = 1)
WHERE rn > 0 AND rn < 10;
Issue is, that the above query does return data which has creation_date as '09-Sep-2015'.
NLS_DATE_FORMAT of my database is 'DD-MON-RR'.
Datatype of the column creation_date is date and the date format in which date is stored is MM/DD/YYYY.
Since your column creation_date has values with non-zero time components, and the result of to_date( '09-Sep-2015', 'DD-MON-YYYY') has a zero time component, the predicate creation_date <= to_date( '09-Sep-2015', 'DD-MON-YYYY') is unlikely to match. As an example, "9/9/2015 1:07:45 AM" is clearly greater than "9/9/2015 0:00:00 AM", which is returned by your to_date() call.
You will need to take into account the time component of the Oracle DATE data type.
One option is to use the trunc() function, as you did, to remove the time component from values of creation_date. However, this may prevent the use of index on creation_date if it exists.
A better alternative, in my view, would be to reformulate your predicate as creation_date < to_date( '10-Sep-2015', 'DD-MON-YYYY'), which would match any time values on the date of 09-Sep-2015.

How to Calculate Gap Between two Dates in SQL Server 2005?

I have a data set as shown in the picture.
I am trying to get the date difference between eligenddate (First row) and eligstartdate (second row). I would really appreciate any suggestions.
Thank you
SQL2005:
One solution is to insert into a table variable (#DateWithRowNum - the number of rows is small) or into a temp table (#DateWithRowNum - the number of rows is high) the rows with a row number (generated using [elig]startdate as order by criteria; also see note #1) plus a self join thus:
DECLARE #DateWithRowNum TABLE (
memberid VARCHAR(50) NOT NULL,
rownum INT,
PRIMARY KEY(memberid, rownum),
startdate DATETIME NOT NULL,
enddate DATETIME NOT NULL
)
INSERT #DateWithRowNum (memberid, rownum, startdate, enddate)
SELECT memberid,
ROW_NUMBER() OVER(PARTITION BY memberid ORDER By startdate),
startdate,
enddate
FROM dbo.MyTable
SELECT crt.*, DATEDIFF(MONTH, crt.enddate, prev.startdate) AS gap
FROM #DateWithRowNum crt
LEFT JOIN #DateWithRowNum prev ON crt.memberid = prev.memberid AND crt.rownum - 1 = prev.rownum
ORDER BY crt.memberid, crt.rownum
Another solution is to use common table expression instead of table variable / temp table thus:
;WITH DateWithRowNum AS (
SELECT memberid,
ROW_NUMBER() OVER(PARTITION BY memberid ORDER By startdate),
startdate,
enddate
FROM dbo.MyTable
)
SELECT crt.*, DATEDIFF(MONTH, crt.enddate, prev.startdate) AS gap
FROM DateWithRowNum crt
LEFT /*HASH*/ JOIN DateWithRowNum prev ON crt.memberid = prev.memberid AND crt.rownum - 1 = prev.rownum
ORDER BY crt.memberid, crt.rownum
Note #1: I assume that you need to calculate these values for every memberid
Note #2: HASH hint forces SQL Server to evaluate just once every data source (crt or prev) of LEFT JOIN.

SSRS 2008: How to count employees on each year

I have a problem where I need to count the number of employees and group on selected years. The years comes from Parameters.
E.g. if i via parameters select 2010-2013, I want to count the number of employees on Dec. 31 on those selected years. The problem is that I am limited to using Fecth from CRM 2013.
On the employees there is employment date and end date but I can’t group on this because it doesn’t tell me how many employees there are on a certain selected year. I also need to make different charts on number of employees and grouping on year.
It's not difficult to use an IIF and calculate the number of employees and put into a specific cell, but I need it to be dynamically.
EDIT: Some more thoughts...
If I use a multivalued parameter and set the available values to the years 2010-12-31…2013-12-31 and on each year I have a selection where I calculate the number of employees. Then I only need to be able to group on this multivalued parameter. Is this possible?
I guest that for your task if you have employee which has end date for example 2011-06-04 than he should be included in report to 2011 year. If I'm right that you need SQL expression like this one:
With Employee AS
(
SELECT 'employee1' as Name, '2010-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee2' as Name, '2010-02-01' as StartDate, '2011-04-01' as EndDate UNION ALL
SELECT 'employee3' as Name, '2010-02-01' as StartDate, '2011-04-01' as EndDate UNION ALL
SELECT 'employee4' as Name, '2011-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee5' as Name, '2011-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee6' as Name, '2011-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee7' as Name, '2011-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee8' as Name, '2012-02-01' as StartDate, '2012-04-01' as EndDate UNION ALL
SELECT 'employee9' as Name, '2012-02-01' as StartDate, '2012-04-01' as EndDate
)
SELECT Employee2.Name AS EmployeeName, YEAR(Employee.StartDate) AS EmployeeWorkedYear
FROM Employee
JOIN Employee as Employee2 ON YEAR(Employee2.EndDate) >= YEAR(Employee.StartDate) AND YEAR(Employee2.StartDate) <= YEAR(Employee.StartDate)
GROUP BY YEAR(Employee.StartDate), Employee2.Name
It will show employee name and year in which he worked. Then you should create dataset with such expression (stored procedure) and group by second column (year) and create grouping table, charts etc.