SELECT ST.Id,
ST.Label,
ST.Asset,
CASE
WHEN ST.RFID = '' THEN 'NULL'
ELSE ST.RFID
END AS RFID,
CASE
WHEN ST.Type = 'O' THEN 'Odometer'
ELSE 'Engine Hours'
END AS AccumulatorType,
ST.AppId,
ST.Timestamp,
ST.Accumulator,
CASE
WHEN ST.Flag = 0 THEN 'Disabled'
WHEN ST.Flag = 1 THEN 'Active'
WHEN ST.Flag = 3 THEN 'Rented'
WHEN ST.Flag = 4 THEN 'Bypass'
WHEN ST.Flag = 5 THEN 'Tanker'
END AS TYPE,
(SELECT COUNT(*)
FROM sync
WHERE RowId = ST.Id
AND DefinitionId = 1
AND Status = 1) AS Updated,
(SELECT COUNT(*)
FROM sync
WHERE RowId = ST.Id
AND DefinitionId = 1
AND Status = 0) AS Remaining
FROM SecondaryTags AS ST
WHERE AppId = @AppId
答案 0 :(得分:0)
为什么要重写逻辑?由于您在外部查询中进行了过滤,因此子查询可能是计算性能最高的方法。
可以通过确保具有写索引来加快子查询的速度。在这种情况下,您需要在sync(RowId, DefinitionId, StatusId)
上建立索引:
create index idx_sync_rowid_definitionid_statusid
on sync(RowId, DefinitionId, StatusId)
您可以将查询重写为:
select . . .,
s.updated, s.remaining
from SecondaryTags st join
(select rowid, sum(status = 1) as updated, sum(status = 0) as remaining
from sync s
where s.definitionId = 1
group by s.rowid
) s
on s.rowid = st.id
where st.AppId = @AppId;
不过,从性能角度来看,我认为索引是一个更好的主意。
答案 1 :(得分:0)
{
"something": "this\nis\na\nsample\nfile"
}