我正在查询以下代码,以获取min,max和avg,但是仍然给我一个问题,因为它查询了name = 'Jose'
中我所拥有的所有行,而不是min,max和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
从第一个查询中得到的示例: Image(无法嵌入图片)
要查询两个日期,我正在使用以下代码,但查询没有任何结果。
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
我正在使用MSSQL数据库。
更新: 正如您在第二个查询中看到的那样,我已经可以在两个日期之间进行查询。问题是我不能只获得最小值,最大值和平均值。 图片:
答案 0 :(得分:0)
如果DATA是DATE字段?
然后将这些日期字符串转换为DATE,而不是转换为VARCHAR。
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-20') AND CONVERT(DATE, '2018-02-25')
AND name = 'Jose'
-- GROUP BY DATA
-- ORDER BY DATA ASC
如果DATA是varchar,那么CONVERT或CAST也会在WHERE子句中执行DATE。
如果只需要1行作为结果,则可以删除select中的GROUP BY,ORDER BY和DATA。
如果DATA是DATETIME,则CAST或CONVERT也将有所帮助。
例如,参见此测试代码段
declare @DT DATETIME = '2018-01-02 12:15:30';
select
IIF(CAST(@DT AS DATE) BETWEEN '2018-01-01' AND '2018-01-02','Yes','No') AS DT_AS_DATE_IS_BETWEEN_DATES
, IIF(@DT BETWEEN '2018-01-01' AND '2018-01-02','Yes','No') AS DT_AS_DATETIME_IS_BETWEEN_DATES;
-- returns the tupple ('Yes' ,'No')
答案 1 :(得分:0)
尝试执行此SQL查询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
答案 2 :(得分:-2)
您可以考虑在查询中进行小的更改
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