SQL can handle AM but no a.m - sql

I have a problem with a database. I'm using SQL Server 2008. A table in the database does have a column to store the time, but since it depends on the windows configuration on client computer, I have records that look like these
id|date |time
1 | 1/1/2013| 3:05:43 PM
2 | 1/1/2013| 3:06:33 PM
3 | 1/1/2013| 4:05:54 PM
4 | 1/1/2013| 7:04:41 PM
5 | 1/1/2013| 3:25:43 p.m.
6 | 1/1/2013| 3:16:33 p.m.
7 | 1/1/2013| 4:55:54 p.m.
8 | 1/1/2013| 7:04:41 p.m.
And I'm using this
convert(varchar, cast([time] as datetime),108)
I have tested a query and it only works with records ending with PM, but results on an error when the query includes a record ending with p.m.
Since it is already implemented software it would be easier to handle this the way it is stored in the database, than use a full datetime data type to store both date and time.

In an ideal world you could change the way they are stored to use a proper DATETIME, but since that isn't an option you could add a REPLACE() in there:
SELECT CAST(REPLACE([time],'.','') AS TIME)
FROM Table1
Demo: SQL Fiddle
If needing the CONVERT():
SELECT CONVERT(VARCHAR(8),CAST(REPLACE([time],'.','') AS TIME),108)
FROM Table1

Related

Write a query in MSSQL to get report for last 30 days

I want to create a report basis on,
Lead Name
Verified By
Verified on
Lead 1
ABC
11-02-2021
Lead 2
KMJ
9-02-2021
Lead 3
ABC
11-02-2021
The report will look like,
Consider today's date as 12-02-2021, we need to create a report for the last 30 days for employees work count
user
12-02-2021
11-02-2021
10-02-2021
9-02-2021
8-02-2021
7-02-2021
so on till last 30 days
ABC
0
2
0
0
0
0
XYZ
0
0
0
0
0
0
KMJ
0
0
0
1
0
0
I have written MSSQL Query as below,
CAST(lead.CREATED_ON as date) between cast(DATEADD(day, -30, getdate()) as date) and CAST(getdate() as date)
but, I am not able to get data in the below format, and also if there no entry for one date that date should show 0 in front of all users
user
12-02-2021
11-02-2021
10-02-2021
9-02-2021
8-02-2021
7-02-2021
so on
Kindly help me to complete this query, if possible kindly share any article link, it will be a great help for me thank you
First of all, are the dates really stored as strings like that? If so, that's a big problem that will make this already-difficult situation much worse. It's important enough you should consider the current schema as actively broken.
Moving on, the most correct way to handle this situation is pivot the data in the client code or reporting tool. That is, return a result set from the SQL database looking more like this:
User | Date | Value
ABC | 2021-02-12 | 0
ABC | 2021-02-12 | 2
ABC | 2021-02-10 | 0
ABC | 2021-02-09 | 0
ABC | 2021-02-08 | 0
ABC | 2021-02-07 | 0
XYZ | 2021-02-12 | 0
XYZ | 2021-02-12 | 0
XYZ | 2021-02-10 | 0
XYZ | 2021-02-09 | 0
XYZ | 2021-02-08 | 0
XYZ | 2021-02-07 | 0
... and so on
And then let the client do the work to reformat this data however you want, rather than asking a server that is often licensed at thousands of dollars per cpu core and isn't suited for the task to do that work.
But if you really must do this on the database server, you should know the SQL language has a very strict requirement to know the number, name, and type of columns in the output at query evaluation time, before looking at any data. Even SELECT * respects this, because the * is based on a table definition known ahead of time.
If the output won't know how many columns there are until it looks at the data, you must do this in 3 steps:
Run a query to get data about columns.
Use the result from step 1 to build a new query dynamically.
Run the new query.
However, since it looks like you always want exactly 30 days worth of data, you may be able to do this in a single query using the PIVOT keyword if you're willing to name the columns something more like OneDayBack, TwoDaysBack, ThreeDaysBack, ... ThirtyDaysBack, such that you can reference them in the pivot code regardless of the current date.

How to go between a set of dates and times

I have a set of data where one column is date and time. I have been asked for all the data in the table, between two date ranges and within those dates, only certain time scale. For example, I was data between 01/02/2019 - 10/02/2019 and within the times 12:00 AM to 07:00 AM. (My real date ranges are over a number of months, just using these dates as an example)
I can cast the date and time into two different columns to separate them out as shown below:
select
name
,dateandtimetest
,cast(dateandtimetest as date) as JustDate
,cast(dateandtimetest as time) as JustTime
INTO #Test01
from [dbo].[TestTable]
I put this into a test table so that I could see if I could use a between function on the JustTime column, because I know I can do the between on the dates no problem. My idea was to get them done in two separate tables and perform an inner join to get the results I need
from #Test01
WHERE justtime between '00:00' and '05:00'
The above code will not give me the data I need. I have been racking my brain for this so any help would be much appreciated!
The test table I am using to try and get the correct code is shown below:
|Name | DateAndTimeTest
-----------------------------------------|
|Lauren | 2019-02-01 04:14:00 |
|Paul | 2019-02-02 08:20:00 |
|Bill | 2019-02-03 12:00:00 |
|Graham | 2019-02-05 16:15:00 |
|Amy | 2019-02-06 02:43:00 |
|Jordan | 2019-02-06 03:00:00 |
|Sid | 2019-02-07 15:45:00 |
|Wes | 2019-02-18 01:11:00 |
|Adam | 2019-02-11 11:11:00 |
|Rhodesy | 2019-02-11 15:16:00 |
I have now tried and got the data to show me information between the times on one date using the below code, but now I would need to make this piece of code run for every date over a 3 month period
select *
from dbo.TestTable
where DateAndTimeTest between '2019-02-11 00:00:00' and '2019-02-11 08:30:00'
You can use SQL similar to following:
select *
from dbo.TestTable
where (CAST(DateAndTimeTest as date) between '2019-02-11' AND '2019-02-11') AND
(CAST(DateAndTimeTest as time) between '00:00:00' and '08:30:00')
Above query will return all records where DateAndTimeTest value in date range 2019-02-11 to 2019-02-11 and with time between 12AM to 8:30AM.

Getting the current date in SQL Server? [duplicate]

This question already has answers here:
How do I get just the date when using MSSQL GetDate()? [duplicate]
(7 answers)
Closed 9 years ago.
How can I get the current date in MS-SQL Server 2008 R2?
The format of the column in my database is DATETIME and dates are stored in the following format:
+++++++++++++ Vrdate ++++++++++
| |
| 2012-11-18 00:00:00.000 |
| 2012-11-19 00:00:00.000 |
| 2013-11-18 00:00:00.000 |
| 2012-12-01 00:00:00.000 |
| 2010-10-09 00:00:00.000 |
| 2012-11-11 00:00:00.000 |
| |
+++++++++++++++++++++++++++++++
I searched but wasn't able to find the way to get the date in this format (i.e. which has the time associated with it in 00:00:00.00). I found GETDATE() function but that provides the current time along with the date as well, what I want is get the date in the following format: CurrentDate 00:00:00.00
How may I get this?
SELECT CAST(GETDATE() AS DATE)
Returns the current date with the time part removed.
DATETIMEs are not "stored in the following format". They are stored in a binary format.
SELECT CAST(GETDATE() AS BINARY(8))
The display format in the question is independent of storage.
Formatting into a particular display format should be done by your application.
As you are using SQL Server 2008, go with Martin's answer.
If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
SQLFiddle

how to get specific number of row data in SQL Server 2005

my table look like
ID Name TakenDateTime
2 critical care 19-Dec-12 11:04:45 AM
3 Pathology 26-Dec-12 5:59:28 PM
4 Radiology 05-Jan-13 7:20:56 PM
5 Cardiology 07-Jan-13 3:54:04 PM
6 Neurology 07-Jan-13 3:56:13 PM
7 Oncology 07-Jan-13 3:56:19 PM
9 Orthopedic 08-Jan-13 5:30:29 PM
10 Cardiothoracic 08-Jan-13 5:30:52 PM
from this table i just want 5th number of row data in SQL Server 2005.
is it possible if yes then please provide me possible way for that.
Any help will be appreciate...
SELECT
ID,
Name,
TakenDateTime
FROM (SELECT
ROW_NUMBER() OVER (ORDER BY Id) AS Row,
*
FROM TableName)
t
WHERE t.Row = 5
Sql Fiddle Demo

Design Hours of Operation SQL Table

I am designing a SQL table to store hours of operation for stores.
Some stores have very simple hours: Monday to Sunday from 9:30AM to 10:00PM
Others are little more complicated. Please consider the following scenario:
Monday: Open All Day
Tuesday: 7:30AM – 2:30PM & 4:15PM – 11:00 PM
Wednesday: 7:00PM – 12:30 AM (technically closing on Thursday morning)
Thursday: 9:00AM – 6:00PM
Friday: closed.
How would you design the table(s)?
EDIT
The hours will be used to showing if a store is open at a user selected time.
A different table can probably handle any exceptions, such as holidays.
The store hours will not change from week to week.
A table like this would be easy for both the output you posted, as well as just firing a bit back (open? yes/no):
Store | Day | Open | Closed
---------------------------
1 | 1 | 0000 | 2400
1 | 2 | 0730 | 1430
1 | 2 | 1615 | 2300
...
Features:
Using 24-hour isn't necessary, but makes math easier.
Store ID would presumably join to a lookup table where you stored Store information
Day ID would translate to day of week (1 = Sunday, 2 = Monday, etc.)
To query for your dataset, just:
SELECT Day, Open, Close... (you'd want to format Open/Close obviously)
To query IsOpen?, just:
SELECT CASE WHEN #desiredtime BETWEEN Open AND Closed THEN 1 ELSE 0 END
FROM table
WHERE store = #Store
Think of it more as defining time frames, days / weeks are more complex, because they have rules and defined start and stops.
How would you define a timeframe?
one constraint (Start[Time and Day]), one reference 'Duration' (hours, minutes,.. of the span)*. Now the shifts (timeframes) can span multiple days and you don't have to work complex logic to extract and use the data in calculations.
**Store_Hours**
Store | Day | Open | DURATION
---------------------------
1 | 1 | 0000 | 24
1 | 2 | 0730 | 7
1 | 2 | 1615 | 6.75
...
1 | 3 | 1900 | 5.5
Do you have to do more than just store and display it?
I think a design which needs to tell if a store is open at a particular time would have to be informed by all of the possibilities, otherwise, you will end up not being able to accommodate something.
What about holiday exceptions?
I would consider storing them as intervals based on a base time (minutes since time 0 on a week).
So 0 is midnight on Monday.
Interval 1 would be 0 - 1440
Interval 2 would be 1890 - 2310
etc.
You could easily convert a user selected time into a minute offset and determine if a store was open.
Your only problem remaining would be interpretation in display for friendly display (probably some extensive logic, but not impossible) and overlap at time 10080 -> 0.