我有一种情况,我需要同时获取列的 min() 和 max() 以及对应于 min() 和 max() 函数的另一列。我已经尝试使用 INNER JOIN 进行查询,使用 min() 或 max() 时都成功了。当两者都被使用时,没有任何返回。
SELECT A.IslandCode, CONVERT(DATE, A.LogTime)LogTime
, MN.Demand MinDemand, MN.TIME MinDemandAt
FROM
(
SELECT IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
) A
INNER JOIN
(
SELECT TOP 1 IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand,
STR(DATEPART(HOUR, LogTime)) + ':' + LTRIM(STR(DATEPART(MINUTE, LogTime))) TIME
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
ORDER BY Demand
) MN
ON A.IslandCode = MN.IslandCode AND A.LogTime = MN.LogTime AND A.Demand = MN.Demand
上述查询返回如下结果,正确
IslandCode LogTime MinDemand MinDemandAt
1 2013-08-13 698 13:0
查询 max()
SELECT A.IslandCode, CONVERT(DATE, A.LogTime)LogTime
, MX.Demand MaxDemand, MX.TIME MaxDemandAt
FROM
(
SELECT IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
) A
INNER JOIN
(
SELECT TOP 1 IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand,
STR(DATEPART(HOUR, LogTime)) + ':' + LTRIM(STR(DATEPART(MINUTE, LogTime))) TIME
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
ORDER BY Demand DESC
) MX
ON A.IslandCode = MX.IslandCode AND A.LogTime = MX.LogTime AND A.Demand = MX.Demand
返回,这也是正确的
IslandCode LogTime MaxDemand MaxDemandAt
1 2013-08-13 1463 20:0
但是当两个查询都在同一个查询中使用时,什么都不返回
SELECT A.IslandCode, CONVERT(DATE, A.LogTime)LogTime
, MX.Demand MaxDemand, MX.TIME MaxDemandAt
, MN.Demand MinDemand, MN.TIME MinDemandAt
FROM
(
SELECT IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
) A
INNER JOIN
(
SELECT TOP 1 IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand,
STR(DATEPART(HOUR, LogTime)) + ':' + LTRIM(STR(DATEPART(MINUTE, LogTime))) TIME
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
ORDER BY Demand DESC
) MX
ON A.IslandCode = MX.IslandCode AND A.LogTime = MX.LogTime AND A.Demand = MX.Demand
INNER JOIN
(
SELECT TOP 1 IslandCode, CONVERT(DATE, LogTime) LogTime, SUM(KiloWatt) Demand,
STR(DATEPART(HOUR, LogTime)) + ':' + LTRIM(STR(DATEPART(MINUTE, LogTime))) TIME
FROM ph_MachineDailyReadings
WHERE IslandCode = 1 AND CONVERT(DATE, LogTime) = '2013-08-13'
GROUP BY IslandCode, LogTime
ORDER BY Demand
) MN
ON A.IslandCode = MN.IslandCode AND A.LogTime = MN.LogTime AND A.Demand = MN.Demand
预期结果
IslandCode LogTime MinDemand MinDemandAt MaxDemand MaxDemandAt
1 2013-08-13 1463 20:0 698 13:0
我可以在单个查询中得到这个结果,还是我需要使用基于存储过程的解决方案?
提前致谢