Get min and max between two dates - sql

I'm querying the following code, to get min, max and avg, but still give me a problem, because it query all rows that I have from name = 'Jose' and not the min, max, and avg.
SELECT CONVERT(CHAR(10), DATA, 120) AS DATA,
MIN([VALUE]) AS MinValue,
AVG([VALUE]) AS MedValue,
MAX([VALUE]) AS MaxValue
FROM databasename
WHERE (name = 'Jose')
GROUP BY CONVERT(CHAR(10), DATA, 120)
ORDER BY DATA ASC
Example of what I get from the first query:
Image (can't embed image)
To query two dates, I'm using the following code but it don't get any result from query.
SELECT CONVERT(CHAR(10), DATA, 120) AS DATA,
MIN([VALUE]) AS MinValue,
AVG([VALUE]) AS MedValue,
MAX([VALUE]) AS MaxValue
FROM databasename
WHERE [DATA] between '2017-02-01' AND '2018-03-10' AND name = 'Jose'
GROUP BY CONVERT(CHAR(10), DATA, 120)
ORDER BY DATA ASC
I'm using MSSQL database.
UPDATE:
I already can query between two dates, as you can see in the second query. Problem that I'm not getting only min, max and avg.
Image:

try this SQL Query Convert(DATE,'2017-02-01').
SELECT DATA AS DATA,
MIN([VALUE]) AS MinValue,
AVG([VALUE]) AS MedValue,
MAX([VALUE]) AS MaxValue
FROM databasename
WHERE [DATA] between CONVERT(DATE, '2017-02-01') AND CONVERT(DATE, '2018-03-10')
AND name = 'Jose'
GROUP BY CONVERT(DATE, '2017-02-20')
ORDER BY CONVERT(DATE, '2017-02-20') ASC

can you consider small change in your query
SELECT CONVERT(CHAR(10), DATA, 120) AS DATA,
MIN([VALUE]) AS MinValue,
AVG([VALUE]) AS MedValue,
MAX([VALUE]) AS MaxValue
FROM databasename
WHERE CONVERT(CHAR(10), DATA, 120) between CONVERT(CHAR(10), 2017 - 02 - 20, 120) AND
CONVERT(CHAR(10), 2018 - 02 - 25, 120) AND name = 'Jose'
GROUP BY CONVERT(CHAR(10), DATA, 120)
ORDER BY DATA ASC

Related

SQL Server Sorting Date With Hours/Mins

I have a complex date column that I need to sort by in SQL Server 2008
My query:
SELECT
DivisionName AS Division, StoreNum AS Store,
LeadName AS Lead, Type, ChangeType, Changes,
UpdatedBy,
CONVERT(VARCHAR(10), UpdatedDate, 101) + RIGHT(CONVERT(VARCHAR(32), UpdatedDate, 100), 8) AS UpdatedDate
FROM
m
WHERE
DivID != 0
ORDER BY
CONVERT(VARCHAR(10), UpdatedDate, 101) + RIGHT(CONVERT(VARCHAR(32), UpdatedDate, 100), 8) ASC
The format in the database: smalldatetime 2016-01-25 16:50:00
And to the display value, I use:
CONVERT(VARCHAR(10), UpdatedDate, 101) + RIGHT(CONVERT(VARCHAR(32), UpdatedDate, 100), 8) AS UpdatedDate
My issue: (Hour/Minute Sorting), I need the 7:40PM row at top.
Different order by attempts:
1: Order by UpdatedDate
2: Order by convert(varchar(10),UpdatedDate, 101) desc, right(convert(varchar(32),UpdatedDate,100),8) asc
The problem is you are converting the datetime into Varchar in sort section also..try below query for your output
SELECT DivisionName as Division, StoreNum as Store, LeadName as Lead, Type, ChangeType,Changes,
UpdatedBy,
convert(varchar(10),UpdatedDate, 101) + right(convert(varchar(32), UpdatedDate,100),8) as UpdatedDate FROM m
WHERE DivID!=0
ORDER by UPDATEdDate desc
here in the order clause mentioned only the datetime column so it will sort the rows in desc order of the date and time..
Sql Fiddle

mssql 2012 how display specific value

i have query
SELECT DATEDIFF(day,
CONVERT(char(10), GetDate(),101),
CONVERT(char(10), fieldname,101))
from tablename
where isdate(fieldname)=1
the output of query is
how i can display only value like 6 from the result???
SELECT DATEDIFF(day, CONVERT(char(10), GetDate(),101), CONVERT(char(10), fieldname,101))
FROM lablename
WHERE isdate(fieldname)=1
AND DATEDIFF(day, CONVERT(char(10), GetDate(),101), CONVERT(char(10), fieldname,101)) = 6
edit 1
SELECT * FROM
( SELECT DATEDIFF(day, CONVERT(char(10), GetDate(),101), CONVERT(char(10), fieldname,101)) AS DateDiff
FROM lablename
WHERE isdate(fieldname)=1
) A
WHERE DateDiff = 6

Query 2 tables from 2 machines and group results

I have a query that gives the right information back but I cannot figure out how to get distinct days and sum the count. below is my query and the results shows what I get back, and what I would like to have come back. I thought the union would join them and give my back the results that I wanted. I have search for quite some time and have not located any help on this topic. Any help will be appreciated. Thank you in advance.
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
group by convert(varchar, log_datetime, 101)
union
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
group by convert(varchar, log_datetime, 101)
order by logdate
Results
235 01/10/2013
312 01/10/2013
3091 01/11/2013
3197 01/11/2013
3339 01/12/2013
3536 01/12/2013
Wanted Results
547 01/10/2013
6288 01/11/2013
6875 01/12/2013
You can try this
SELECT SUM(icount) AS icount, logdate FROM
(
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
FROM openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
GROUP BY convert(varchar, log_datetime, 101)
UNION ALL
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
FROM openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
GROUP BY convert(varchar, log_datetime, 101)
) AS tbl
GROUP BY logdate
ORDER BY logdate
And here is sqlfiddle
SELECT count(1) icount, AA.logdate FROM
(
SELECT CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
union all
SELECT CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
) AA
group by AA.logdate order by AA.logdate
I believe peterm's answer is correct, just wanted to add a note as to why.
With SQL, you have to think in sets. You are creating two unique sets of data, and, using UNION, combining them. However, your GROUP BY statements are within each set, not the combination. Hence, the multiple row results. By wrapping everything with another SELECT statement, you are querying the combined set, and are now able to group and aggregate.

How to build this sql query

i want to find the records in sql
from say 25-08-2012 to 01-09-2012
and i want to group by date
here is my query
SELECT CONVERT(VARCHAR(10), date, 105) AS dt,
COUNT(id) AS cnt
FROM tablename
WHERE date BETWEEN CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
AND CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
GROUP BY CONVERT(VARCHAR(10), date, 105)
i am getting result as
dt cnt
01-09-2012 48
27-08-2012 1
28-08-2012 3
29-08-2012 11
30-08-2012 3
but expect it as
dt cnt
25-08-2012 0
26-08-2012 0
01-09-2012 48
27-08-2012 1
28-08-2012 3
29-08-2012 11
30-08-2012 3
How i can modify above query
i also tried with CASE but no luck
Many Thanks..
The reason you are missing these dates in result is that there's no data for them in your table, however, the following would insure you are getting all of the dates in specified range:
CREATE TABLE #tmp_dates ([date] datetime)
DECLARE #dt_start datetime, #dt_end datetime, #dt_dif int
SET #dt_start = CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
SET #dt_end = CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
SET #dt_dif = datediff(day,#dt_start,#dt_end)
WHILE #dt_dif >= 0 BEGIN
INSERT INTO #tmp_dates
SELECT dateadd(day,#dt_dif,#dt_start)
SET #dt_dif = #dt_dif - 1
END
SELECT CONVERT(VARCHAR(10), t2.[date], 101) AS dt, COUNT(t1.id) AS cnt
INTO #tmp_result
FROM tablename t1
RIGHT OUTER JOIN #tmp_dates t2
ON CONVERT(VARCHAR(10), t1.[date], 101) = CONVERT(VARCHAR(10), t2.[date], 101)
GROUP BY CONVERT(VARCHAR(10), t2.[date], 101)
ORDER BY CONVERT(DATETIME,CONVERT(VARCHAR(10), t2.[date], 101)) ASC /* DESC */
SELECT convert(VARCHAR(10),CONVERT(DATETIME,dt),105) as dt,cnt FROM #tmp_result
DROP TABLE #tmp_dates
DROP TABLE #tmp_result
Your query cannot be directly modified to return the data you want. To count the dates in question, there must be records in the target table actually having those dates; in your case, however, the dates are merely parameters in the query. As a result, there is no way to incorporate them into your result set.
You must create a secondary table that includes all the dates for which you want data, and then recharacterize your query as a left outer join from that date table to your target table. This will, in turn, give you the zero counts for the dates present in the "date" table, but absent from the target table.
How about using IsNull()? Let me know if this works.
SELECT CONVERT(VARCHAR(10), date, 105) AS dt,
ISNULL(COUNT(id),0) AS cnt
FROM tablename
WHERE date BETWEEN CONVERT(DATETIME, '21-08-2012 00:00:00:000',103)
AND CONVERT(DATETIME, '01-09-2012 23:59:00:000' ,103)
GROUP BY CONVERT(VARCHAR(10), date, 105)

How do I group DATE field by YEAR-MM in SQL Server?

I have a date field in a query and I do want to get GROUP BY report like this:
DATE COUNT
2010-01 10
2010-02 2
...
2010-12 24
2012-13 34
What is the proper syntax to obtain this on SQL Server?
All these conversions to string work, but I find this method more efficient, albeit less readable:
SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0), COUNT(*)
FROM dbo.TheTable
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0);
If you don't want to repeat the expression, then:
;WITH x AS (SELECT m = DATEADD(MONTH, DATEDIFF(MONTH, 0, [DATE]), 0)
FROM dbo.TheTable)
SELECT m, COUNT(*)
FROM x GROUP BY m;
This way the output is still a date/time value and can be used that way for other things. And it doesn't involve any messy string conversions.
CONVERT(VARCHAR(7), CreationDate, 120) as Date
You can simply do:
select convert(char(7), #myDate, 20)
Example
declare #myDate as DateTime
set #myDate = '2012-06-23'
select convert(char(7), #myDate, 20)
Output
-------
2012-06
So the full statement would look like:
select convert(char(7), myDate, 20), count(*) as Count
from MyTable
group by convert(char(7), myDate, 20)
Update
The sample data includes the value 2012-13. I am going to assume this is a typo and that the number after the dash represents the month.
SELECT CAST(DATEPART(year, dateCol) as VARCHAR) + '-' + CAST(DATEPART(month, dateCol) as VARCHAR) as Date, count(*) As Count
FROM myTable
GROUP BY CAST(DATEPART(year, dateCol) as VARCHAR) + '-' + CAST(DATEPART(month, dateCol) as VARCHAR)