我有一个查询,基本上是按天分组总和
SELECT CountDate, SUM(Max_Count) as MaximumCount, SUM(Min_Count) as MinimumCount
FROM countTable
WHERE countId IN ('48', '34', '65', '63', '31', '64', '86')
AND CountDate BETWEEN '2014-08-14' AND '2014-08-16'
GROUP BY CountDate
ORDER BY CountDate
输出结果为
Date | Maximum | Minimum
------------|-----------|----------------------
2014-08-14 | 3018234 | 3014212
2014-08-15 | 3023049 | 3018510
2014-08-16 | 3026813 | 3023244
我希望查询能够获得最后一天的MaximumCount与第一天的MinimumCount之间的差异。
查询结果应为最后一天的最大值,即2014-08-16:3026813减去( - )第一天的最小值,即2014-08-14 | 3014212.因此3026813 - 3014212
任何帮助我如何实现这一点将非常感激。
答案 0 :(得分:1)
SELECT
(SELECT [Maximum] FROM TABLE WHERE Date = (SELECT MAX(Date) FROM TABLE)) -
(SELECT [Minimum] FROM TABLE WHERE Date = (SELECT MIN(Date) FROM TABLE))
FROM TABLE
答案 1 :(得分:0)
我认为这是正确的。
DECLARE @STARTDATE DATE = '2014-08-14'
DECLARE @ENDDATE DATE = '2014-08-16'
SELECT A.CountDate,
B.MaximumCount - A.MinimumCount
FROM (
SELECT CountDate,
SUM(Max_Count) AS MaximumCount,
SUM(Min_Count) AS MinimumCount,
FROM countTable
WHERE countId IN ('48','34','65','63','31','64','86')
AND CountDate BETWEEN @STARTDATE AND @ENDDATE
GROUP BY CountDate) A
LEFT JOIN (
SELECT DATEADD(DAY,CountDate,1) CountDate
SUM(Max_Count) AS MaximumCount,
SUM(Min_Count) AS MinimumCount,
FROM countTable
WHERE countId IN ('48','34','65','63','31','64','86')
AND CountDate BETWEEN BETWEEN @STARTDATE AND @ENDDATE
GROUP BY DATEADD(DAY,CountDate,1)) B
ON A.CountDate = B.CountDate
答案 2 :(得分:0)
参考Jithin Shaji的回答,我已经得到了这个查询的结果
DECLARE @STARTDATE DATE = '2014-08-14'
DECLARE @ENDDATE DATE = '2014-08-16'
DECLARE @NOOFDAYS INT = datediff(day, @STARTDATE, @ENDDATE)
SELECT A.CountDate,
A.MaximumCount - B.MinimumCount AS CountSum
FROM (
SELECT CountDate,
SUM(Max_Count) AS MaximumCount,
SUM(Min_Count) AS MinimumCount
FROM countTable
WHERE countId IN ('48','34','65','63','31','64','86')
AND CountDate BETWEEN @STARTDATE AND @ENDDATE
GROUP BY CountDate) A
LEFT JOIN (
SELECT DATEADD(DAY, @NOOFDAYS, CountDate) AS CountDate,
SUM(Max_Count) AS MaximumCount,
SUM(Min_Count) AS MinimumCount
FROM countTable
WHERE countId IN ('48','34','65','63','31','64','86')
AND CountDate BETWEEN @STARTDATE AND @ENDDATE
GROUP BY DATEADD(DAY, @NOOFDAYS, CountDate)) B
ON A.CountDate = B.CountDate