I'm new to SQL, learning the basics. I searched, but did not find the exact answer I needed that would work.
I have a table that shows customers who have purchased products and the datetime they were purchased. The column is called SaleDate. The format (for example) of the datetime looks like this:
2015-08-21 00:00:00.000
2014-03-17 00:00:00.000
I need to use a query to only show the products purchased during December of 2015. I don't think the SELECT or FROM statements are relevant to my question. Here are the two WHERE clauses I tried. Neither of these worked.
WHERE SaleDate = '2015-12%'
WHERE SaleDate = '%Dec-2015%'
You can use BETWEEN:
WHERE SaleDate BETWEEN '2015-12-01 00:00:00' AND '2016-01-01 00:00:00'
Use YEAR and MONTH functions
... WHERE YEAR(SaleDate) = 2015 AND MONTH(SaleDate) = 12
Don't use BETWEEN because you must to express the dates as literals, and that will be a problem considering that your SaleDate column could come with the time part in the future...
Related
As the title says, can I create a new column from two fields? For example, I created a new column from the master values table to represent the months, and I have another column with the year. Can I combine them to create a date with whatever day? What I have is on the left, what I want is on the right:
Month Year NewDate
---- ---- -------
3 2015 2015-03-01
4 2015 2015-04-01
Whenever I tried to cast the month as datetime, it would look like this:
1900-01-03
This is probably a dumb question, but I created a timeline that lists out the months, and the trouble lies whenever the end date parameter chosen is less than the start date parameter, such as December 2015 to January 2016. I created the report in SSRS and the parameters aren't quite working correctly. Thanks guys!
Also, here's a snapshot of what the timeline looks like:
SELECT
DATEFROMPARTS ( [Year], [Month], 1 ) AS NewDate
FROM
YourTable
;
select dateadd(mm, t.Month -1, dateadd(yy,t.Year-1900,'19000101'))
from table1 t
I have a little problem with my SQL Query:
I have this value on my table: 2014-10-23 00:00:00
I have a record like this each 2 minutes every day, and I need to SELECT all the value of today.
Now I made this:
WHERE mytable.data LIKE CURDATE()
and it doesn't work. I tried a lot of things found here on stackoverflow and nothing could help me.
Thanks for answer.
You don't say which version of SQL Server you are using, if you have the DATE data type available you can cast the datetime returned by getdate() or CURRENT_TIMESTAMP to strip off the time part.
But then you need a range to find all the matching rows, something like:
SELECT *
FROM mytable
WHERE mytable.data >= CAST(GETDATE() AS date)
AND mytable.data < CAST(DATEADD(day, 1, GETDATE()) AS date)
SQL Fiddle
I am trying to order by Date in SQL Server I am facing a weird issue. There are 2 cases I should explain to help you understand my issue .
Case 1 :
select [MonthName]
from prod.[dim date]
where F_Year = 2014
order by [Date]
My output:
june june june july july july july august
// Here I get duplicates but order by is working as expected
Case 2 : tried to remove duplicates by using "distinct"
select distinct [MonthName]
from prod.[dim date]
where F_Year = 2014
order by [Date]
My output:
August july june
// Order By not working as expected (ordering alphabetical wise ) .
Any workaround is appreciated
Firstly your query seems to be working off a table with 3 fields representing possibly a single date or maybe 2 - hard to tell without the structure but I can see : F_Year, [Date] & [MonthName]. So if these actually represent a single date, then revert to that single date and use formatting to determine F_Year and MonthName.
Secondly check out these posts for a probable answer to your question:
Sort by Date in SQL
Convert Month Number to Month Name Function in SQL
I have a table in my database. This table is called Order. It has a structure like this
ID
CustomerID
OrderDate
Quantity
Price
I need to get all of the orders for the past 2 weeks. How do I do that? I don't understand how to work with dates in this manner in SQL.
Thank you!
You could incorporate something like this into your WHERE clause:
WHERE OrderDate >= DATEADD(day,-14,GetDate())
(i.e OrderDate is more recent than today minus 14 days.)
[I don't have access to SQL Server here so I can't check it - but it might work :)]
Edit: Depending on the exact datatype of OrderDate, I'm not sure what will happen in cases where you have e.g. an order half way through the day two weeks ago, so you might want to check what happens.
marnir answer is the way to do it but this is another option excluding OrderDate > today:
select * from Order
where [OrderDate]
BETWEEN DATEADD(dd, -14, GetDate()) AND GetDate()
Here is another possible way of retrieving orders placed in the last 2 weeks. This is assuming that OrderDate is a column of data type datetime. Screenshot #1 shows sample data in a table named dbo.[Order] similar to your requirements and output of below query against that table data. This query was tested in SQL Server 2008 R2 but is compatible with other SQL Server versions as well.
SELECT Id
, CustomerId
, OrderDate
, Quantity
, Price
FROM dbo.[Order]
WHERE DATEDIFF(WEEK, OrderDate, GETDATE()) <= 2
Hope that helps.
Screenshot #1
How I can calculate the working time in SQL Server between two datetime variables, excluding the holidays?
Any ideas?
Holidays aren't universal - they depends very much on your location. Not even the fact which days of the week are "working" days is the same - it depends on your location.
Because of that, a general, universal answer will not be possible, and for that reason, there's also no system-provided function in T-SQL for doing this. How would SQL Server know what holidays you have in your corner of the world??.
You need to have a table of your holidays somewhere in your system and handle it yourself.
Some posts that might be of some help to you:
Calculate Number of Working Days in SQL Server: this just basically removes any Saturdays and Sundays - but doesn't include other holidays
How do I count the number of business days between two dates? : shows the same main approach, with the addition of a table that contains other holidays like Easter, 4th of July (US National Holiday) and so on
Like marc_s says, you currently need a custom solution. I really hope Microsoft adds some standard functionality: it's tough to get right, and holidays are pretty much standardized by location.
Here's an example:
declare #start_date datetime
declare #end_date datetime
set #start_date = '2010-12-20'
set #end_date = '2010-12-26'
-- A table with all non-working days. This just adds Christmass, but you
-- probably should add weekends as well.
declare #non_working_days table (dt datetime)
insert #non_working_days values ('2010-12-25'), ('2010-12-26')
-- Remove the time part
set #start_date = DATEADD(D, 0, DATEDIFF(D, 0, #start_date))
set #end_date = DATEADD(D, 0, DATEDIFF(D, 0, #end_date))
-- Find the number of non-working-days
declare #nwd_count int
select #nwd_count = count(*)
from #non_working_days
where dt >= #start_date and dt < #end_date
-- Print result
select datediff(DAY, #start_date, #end_date) - #nwd_count
This prints 5, because the 25th is not a working day.
Have a table which has a row for every date you're interested in, and, say, a "working hours" column, or just a "working day" indicator if you want to do it at day granularity. (I find this approach makes the final SQL simpler, plus enables all sorts of other useful queries, but then I'm into data warehousing, rather than operational databases, so you may find the "just list the holidays" approach better, depending...)
You will, of course, have to create that table yourself, working from some feed of holiday dates for the region you're interested in.
Typically you can project these forward at least a year, as most public holidays are agreed a long way in advance (though there are some that pop up at the "last minute" -- in the UK, for example, 29 April will be an extra public holiday in 2010, as there's a royal wedding taking place, and we got less than a year's notice of that.
Then you just
SELECT
SUM(working_hours)
FROM
all_dates
WHERE
the_date BETWEEN #start_date AND #end_date
If you want to do this internationally, it gets incredibly difficult to get your data; there's no sensible source that I know of for international holiday dates, and different regions in a "country" might have different dates -- e.g. you may know that someone's in the United Kingdom, but unless you know if they're in Scotland or not, you won't know if the first two days of the year are a public holiday, or just the first...