SQL Assistance - SELECT/WHERE/CASE? - sql

I am banging my head against the desk here trying to work something out in SQL, I understand the logic and I can easily complete the task in Excel however where is the fun in that :)
The database in question as a WorkOrder table and I am selecting the following columns:
SELECT WorkOrderNumber,
WorkOrderDescription,
WorkOrderHistoryDescription,
RaisedDateTime,
FinishedDateTime
What I need I am trying to do is return all work orders raised within a given month which is easy enough:
WHERE RaisedDateTime >= CONVERT(DATETIME, '2014-12-01' ) and <= CONVERT(DATETIME, '2014-12-31' )
The kicker is I also want those return those records that were raised prior to but were closed in the given month, I tried the following which appeared to work:
WHERE ( RaisedDateTime >= CONVERT(DATETIME, '2014-12-01' ) AND RaisedDateTime <= CONVERT(DATETIME, '2014-12-31' ) )
OR ( FinishedDateTime >= CONVERT(DATETIME, '2014-12-01' ) AND FinishedDateTime <= CONVERT(DATETIME, '2014-12-31' ) AND RaisedDateTime < CONVERT(DATETIME, '2014-12-01' ) )
However when I inserted PreventativeMaintenanceID IS NULL after the statement above I found work orders that had a value in that column, if I just have the first line of the WHERE statement everything works fine.
Any ideas/pointers of where I might be going wrong? I was looking to see if I could use a CASE statement however I just couldn't get it to work.

It's hard to tell without knowing how exactly your full query looks but try grouping your criteria other than that line, and then add that line after the grouped criteria, like this:
SELECT WorkOrderNumber,
WorkOrderDescription,
WorkOrderHistoryDescription,
RaisedDateTime,
FinishedDateTime
from tbl
WHERE (
(RaisedDateTime between CONVERT(DATETIME, '2014-12-01') AND
CONVERT(DATETIME, '2014-12-31')) OR
(FinishedDateTime between CONVERT(DATETIME, '2014-12-01') AND
CONVERT(DATETIME, '2014-12-31') AND
RaisedDateTime < CONVERT(DATETIME, '2014-12-01'))
)
and PreventativeMaintenanceID IS NULL
Based on your description it sounds like an order of operations issue due to the OR

Related

Select data from date range between two dates and times

I have pretty much the exact same question as logged here
Select data from date range between two dates
But when I used the solution given it does not work for me. Only difference is that my table has date and time in the one column. So I want to be able to return all values that fall within the date range
I have this so far but not working
SELECT * FROM aview
WHERE startDate BETWEEN ('2017-11-25 11:27:00.000', '2018-11-25 11:27:00.000') OR
leftdate BETWEEN ('2017-11-25 11:27:00.000', '2018-11-25 11:27:00.000') OR
start_Date <= '2017-11-25 11:27:00.000' AND left_dept_date >= '2018-11-25 11:27:00.000'
I've never seen BETWEEN(from,to) as a pattern in an sql query - you're making it look like a function call similar to SUBSTRING(column, index) when it doesn't work like that. Try this:
SELECT * FROM aview
WHERE
startDate BETWEEN CONVERT(datetime, '2017-11-25 11:27:00.000', 121) AND CONVERT(datetime, '2018-11-25 11:27:00.000', 121) OR
leftdate BETWEEN CONVERT(datetime, '2017-11-25 11:27:00.000', 121) AND CONVERT(datetime, '2018-11-25 11:27:00.000', 121) OR
start_Date <= CONVERT(datetime, '2017-11-25 11:27:00.000', 121) AND left_dept_date >= CONVERT(datetime, '2018-11-25 11:27:00.000', 121)
There's no syntax error with this query (see http://sqlfiddle.com/#!6/9eecb7db59d16c80417c72d1e1f4fbf1/16114 ) when the columns are proper dates, so the only thing left is a flaw in the view code, doing a bum conversion of data - for example if your view is converting a string of "12/31/2017" into a date, but doing it as if it was "dd/mm/yyyy", or perhaps converting a "2107-12-31" with a typo in the year, into a smalldatetime type that doesn't support years beyond 2079
See https://learn.microsoft.com/en-us/sql/t-sql/language-elements/between-transact-sql
I am not sure about syntax for BETWEEN Clause is upgraded in sql Server 2012. but it seems like that you have syntax error in between clause
SELECT *
FROM aview
WHERE ( startDate BETWEEN '2017-11-25 11:27:00.000' AND '2018-11-25 11:27:00.000' AND
leftdate BETWEEN '2017-11-25 11:27:00.000' AND '2018-11-25 11:27:00.000' ) OR
start_Date <= '2017-11-25 11:27:00.000' AND
left_dept_date >= '2018-11-25 11:27:00.000'
You copied the wrong answer. The BETWEEN syntax is invalid.
Then if you want to know whether a record's range overlaps with a given range, why are there four columns in your table and query? It should be two: the start and the end.
SELECT *
FROM aview
WHERE start <= '2018-11-25T11:27:00.000' AND end >= '2017-11-25T11:27:00.000';
Or if you want the record's whole range within the given range:
SELECT *
FROM aview
WHERE start >= '2017-11-25T11:27:00.000' AND end <= '2018-11-25T11:27:00.000';
SELECT * FROM USERContracts C
WHERE
(C.UCFromDate > ='2008-01-01' AND C.uCFromDate <='2020-02-06' )
OR (C.UCToDate < ='2008-01-01' AND C.uCToDate >='2020-02-06')
order by USERID

How to convert datetime type column in int so it can be used with '> < =' operators

I need this SQL to be able to have additional condition:
select sum(cost) as totalCost from monthly_costs_tracker
where date_of_month <= CURRENT_TIMESTAMP
I want to be able to add an 'and' operator after CURRENT_TIMESTAMP for example:
select sum(cost) as totalCost from monthly_costs_tracker
where date_of_month <= CURRENT_TIMESTAMP and date_of_month >= '2017-11-01%'
EDITED: So I need this query to track the entered values in a column 'costs'.
It calculates the sum of all entered records. I want to upgrade it by setting a time period on which to calculate.
For example when December, comes I need the calculation of the sum to take place only in records with date > 2017-12
To get month-to-date:
select sum(cost) as totalCost
from monthly_costs_tracker
where date_of_month <= getdate() and
date_of_month >= dateadd(day, 1 - day(getdate()), cast(getdate() as date)
Or, you can use datefromparts():
select sum(cost) as totalCost
from monthly_costs_tracker
where date_of_month <= getdate() and
date_of_month >= datefromparts(year(getdate), month(getdate), 1);
Feel free to use CURRENT_TIMESTAMP. I'm just in the (perhaps bad) habit of using getdate() in SQL Server.
You should never use like on dates. If you feel the need, explicitly convert to a string before hand (although that is almost never necessary).
According to your query I think you want:
select sum(cost) totalCost
from monthly_costs_tracker
where (date_of_month <= CURRENT_TIMESTAMP)
and (REPLACE(CONVERT(VARCHAR, date_of_month, 102), '.', '-') > '2017-11%');
You can see CAST and CONVERT to see the styles.

SQL Server date setting

running to a small issue.
I have a scrpit that based on date. what i need is to retrieve data that is 14 days ago not including the date it was run.
example; date run 12/15/2016 should retrieve Data between 12/1/2016 - 12/14/2016.
The issue i have is it ends with the date was run. see below the criteria I set.
where a.UF_1 <> '' and (DATEDIFF(dd, a.TRANSACTION_DATE, getdate()) <14)
any help is appreciated.
Thank you.
select * from yourTable
where datecolumn < getdate()
and datecolumn >=dateadd(dd,-14,getdate())
OR . . . .
declare #someDateVariable datetime - '12/15/2016'
select *
from yourTable
where cast(datecolumn as date) < cast(#someDateVariable as date)
and datecolumn >= dateadd(dd,-14,#someDateVariable)
Do you mean like this:
where a.UF_1 <> '' and cast(a.TRANSACTION_DATE as date) between cast(getdate()-14 as date) and cast(getdate()-1 as date).
I assume that neither a.UF_1 or a.TRANSACTION_DATE is nullable.. otherwise handle this.

SQL Server 2005 extract a date from a string

I have a view I am creating and I want to group by an extracted date from a column that has a date and time. This is where I am....
SELECT
ClockCode AS MOnum, SUM(Actual_Hrs) AS Runtothours, TStamp
FROM
dbo.Raw_Booking
WHERE
(Actual_Hrs > 0) AND (ClockCode LIKE 'MO%')
AND (TStamp > CONVERT(DATETIME, '2013-01-01 00:00:00', 102))
GROUP BY
ClockCode, TStamp
so while I have it grouped by the TStamp column there is a record for each one based on the time... I am looking to get a total amount of run time for each order by date.
The TStamp column is formatted as:
2013-01-02 08:18:47.000
If you can change your schema, store it as a date to begin with. Otherwise, change your group by clause to something similar to...
GROUP BY CAST(TStamp AS DATE)
EDIT: Forgot you were in SQL 2005. You can still do something like the following, but keep in mind this should be considered an ugly, short-term, workaround. All the comments in this thread about redesigning are completely valid and should be pursued...
GROUP BY SUBSTRING(TStamp, 0, 11)
SELECT ClockCode AS MOnum
, SUM(Actual_Hrs) AS Runtothours
, TStampDate
FROM dbo.Raw_Booking
CROSS APPLY (
SELECT CONVERT(datetime, TStamp, 102) AS TStampDateTime
) AS CA1
CROSS APPLY (
SELECT DATEADD(day, DATEDIFF(day, 0, TStampDateTime), 0) AS TStampDate
) AS CA2
WHERE Actual_Hrs > 0
AND ClockCode LIKE 'MO%'
AND TStampDateTime > CONVERT(DATETIME, '2013-01-01 00:00:00', 102))
GROUP BY ClockCode
,TStampDate

SQL date question

I have a question. I have a SQL Server 2008 table with a field column. I have for example the Following dates:
1/1/2001
5/5/2004
8/5/2009
10/7/2011
5/5/2012
1/13/2014
Id like to be able to show all dates >= the current date (7/29/2011) as well as largest table date that is < current date. In this example, the result would be all dates >= 8/5/2009.
Can someone help guide me please??
select max(date) [date] from table where date < getdate()
union
select date from table where date >= getdate()
If I understand correctly, you want to include the date prior to the current date. GETDATE() will get the current date (with time). If you're alright with that, then this should work. Otherwise, you may have to parse out just the date from GETDATE()
SELECT TheDate
FROM DateTable
WHERE TheDate >= (SELECT MAX(TheDate) FROM DateTable WHERE TheDate < GETDATE())
This gets all dates greater than or equal to the most recent date before the current date.
I am not entirely sure I understand, but this looks like a BETWEEN the relevant dates. Or is there something more I am missing?
Assuming your table is called DateTable and your field is called TheDate, do it like this:
SELECT TheDate
FROM DateTable
WHERE TheDate >= DATEADD(d, -2, GETDATE())
Good luck!
It depends on the SQL server you're using. In postgres, for example, you need something like
SELECT fields FROM table WHERE date_field >= CURRENT_DATE - 1
But other SQL servers have different ways to specify "yesterday"
SELECT d1.*
FROM dates d1
LEFT JOIN dates d2 ON d1.Date < d2.Date AND d2.Date < GETDATE()
WHERE d2.Date IS NULL
Explanation:
Select every date for which there does not exist a date that is both earlier than today and later than the one being inspected.
Lots of guessing here based on loose narrative and unknown data types.
DECLARE #t TABLE(d DATE);
INSERT #t SELECT '20010101'
UNION ALL SELECT '20040505'
UNION ALL SELECT '20090805'
UNION ALL SELECT '20111007'
UNION ALL SELECT '20120505'
UNION ALL SELECT '20140113';
DECLARE #now DATE = SYSDATETIME();
WITH t AS
(
SELECT d, rn = ROW_NUMBER() OVER (ORDER BY d)
FROM #t
)
SELECT t.d
FROM t LEFT OUTER JOIN t AS x
ON t.rn = x.rn - 1
WHERE COALESCE(x.d, #now) >= #now
ORDER BY t.d;