我是SQL查询的新手,我需要从这个查询开始进行连接:
SELECT b.Name AS VehicleName,
a.*
FROM VehicleDay AS a
INNER JOIN
Vehicles AS b
ON a.VehicleId = b.Id
WHERE b.SiteId = 100
AND a.Day >= '2016-04-22'
AND a.Day < '2016-04-28';
并在Info数据表中添加6个列:
开始(当天的第一个值)&amp;结束(最后一天) - 累积[Cml] - 当前容量[Cap] - 总电荷[Chrg]
所以我需要在最右边添加 S Cml | E Cml | S Cap | E Cap | S Chrg | E Chrg
在Info表中,我在不同的时段获得相同VehicleId的值,我需要在日期范围内选择每天的第一个和最后一个数据。
到目前为止,我的查询看起来像这样:
SELECT b.Name AS VehicleName,
a.*,
c.MaxDay,
c.Cumulative,
c.CurrentCapacity,
c.TotalCharge
FROM VehicleDay AS a
INNER JOIN
Vehicles AS b
ON a.VehicleId = b.Id
INNER JOIN
(SELECT VehicleId,
MAX(TimestampLocal) AS MaxDay,
CAST (TimestampLocal AS DATE) AS Day,
Cumulative,
CurrentCapacity,
TotalCharge
FROM Info
GROUP BY VehicleId,
CAST (TimestampLocal AS DATE),
Cumulative, CurrentCapacity, TotalCharge) AS c
ON a.VehicleId = c.VehicleId
AND a.Day = c.Day
WHERE b.SiteId = 100
AND a.Day >= '2016-04-22'
AND a.Day < '2016-04-28';
但第二个查询返回的行数与第一个相同,我需要将行数显示为第一个。
我是否可以在不添加更多行的情况下将这6列添加到查询中?
答案 0 :(得分:1)
重复的原因是您还要按Cumulative, CurrentCapacity, TotalCharge
分组,GROUP BY
可能在同一天有不同的值。那么Info
每天将提供多个记录,因此将已经从其他两个表中选择的记录相乘。
您可以先获取时间戳的MIN / MAX值,然后使用这些值再次加入表SELECT b.Name AS VehicleName,
a.*,
c.S_Time,
c.E_Time,
s.Cumulative AS S_Cml,
e.Cumulative AS E_Cml,
s.CurrentCapacity AS S_Cap,
e.CurrentCapacity AS E_Cap,
s.TotalCharge AS S_Chrg,
e.TotalCharge AS E_Chrg
FROM VehicleDay AS a
INNER JOIN Vehicles AS b
ON a.VehicleId = b.Id
LEFT JOIN (SELECT VehicleId,
CAST (TimestampLocal AS DATE) AS Day,
MIN(TimestampLocal) AS S_Time,
MAX(TimestampLocal) AS E_Time
FROM Info
GROUP BY VehicleId,
CAST (TimestampLocal AS DATE)
) AS c
ON a.VehicleId = c.VehicleId
AND a.Day = c.Day
LEFT JOIN Info AS s
ON s.VehicleId = c.VehicleId
AND s.TimestampLocal = c.S_Time
LEFT JOIN Info AS e
ON e.VehicleId = c.VehicleId
AND e.TimestampLocal = c.E_Time
WHERE b.SiteId = 100
AND a.Day >= '2016-04-22'
AND a.Day < '2016-04-28'
两次,一次检索与MIN时间相关的列,一次用于那些与MAX时间相关:
VehicleId
有一个条件:组合TimestampLocal
和#!/bin/bash
rsync -av -e "ssh " $1 user@computer.domain.org:$2
必须是唯一的,否则您仍会获得比预期更多的行。