我有两个表BaseVehicle和Version_Main,它们之间没有关联
我需要获取Count of Count(BaseVehicleId),SUM(BaseVehicleID),Count(NewAddedBaseVehicles),Count(DeletedBaseVehicles)
Count,BaseVehicleID的总和,我可以从下面的查询中获取它,
Select SUM(DISTINCT CAST(BaseVehicleID as BIGINT)),
COUNT(DISTINCT BaseVehicleID)
from BaseVehicle
从版本日期起新增基础车辆的数量,我可以从以下查询中获取,
Select COUNT(DISTINCT BaseVehicleId)
from BaseVehicle BV, Version_Main Ver1
Where Ver.Version_Date IN (Select top 1 Version_Date
from [Version_Main]
order by Version_Date desc) and
BV.InsertDate > Ver.VCDB_Version_Date
从版本日期算起新删除的基础车辆,我可以从以下查询中获取,
Select COUNT(DISTINCT BaseVehicleId)
from BaseVehicle BV, Version_Main Ver
Where Ver.Version_Date IN (Select top 1 Version_Date
from [Version_Main]
order by Version_Date desc) and
BV.InsertDate > Ver.Version_Date and BV.DeleteDate IS NOT NULL
我的表格结构如下,
我可以将这些查询组合在一起查询数据吗?
这将是我预期的结果表
答案 0 :(得分:0)
其中一个SQL技巧是将CASE与aggregate function合并。
例如:
select
count(distinct BV.BaseVehicleID) as Count_BaseVehicle,
sum(distinct CAST(BV.BaseVehicleID as BIGINT)) as Sum_BaseVehicle,
count(distinct case when BV.InsertDate > Ver.VersionDate and BV.DeleteDate is null then BV.BaseVehicleID end) as Count_NewBaseVehicle,
count(distinct case when BV.InsertDate > Ver.VersionDate and BV.DeleteDate is not null then BV.BaseVehicleID end) as Count_DeletedBaseVehicle
from BaseVehicle BV
cross join (select max(VersionDate) as VersionDate from Version_Main) Ver;
虽然我没有得到标识符总和的目的。