我有一个相对独特的问题,虽然我已经找了2天但我找不到正确的答案。
在我当前的项目中,我使用活动报告6从存储在SQL服务器上的数据创建报告。
我试图使用一个没有运气的select distinct语句。
我使用SQL创建视图,但是我没有将其保存为视图,每次请求报表时,代码本身都将作为查询运行。
报告将显示公司租赁的所有现有车辆。因此,报告必须仅在注册字段中带回独特的点击。因为它可以在那里多次,如果超过1人驾驶该车辆等。
这是我的sql代码
select distinct on Registration from CompanyCars
CompanyCars.Registration as Regno,
[Staff Details].[first Name] + ' ' + [Staff Details].[Last Name] as Driver,
CompanyCars.Car_Type as VehicleType,
CompanyCars.Reg_Date as Regdate,
CompanyCars.Price as Price,
[Staff Details].[NI Number] as NInumber,
CompanyCars.End_Mile - CompanyCars.Start_Mile as UsedMiles,
CompanyCars.Lease_Mile -(CompanyCars.End_Mile - CompanyCars.Start_Mile) as ExcessMiles,
case when CompanyCars.Lease_Mile -(CompanyCars.End_Mile - CompanyCars.Start_Mile) < 0 and CompanyCars.Excess <> 0 then (CompanyCars.End_Mile - CompanyCars.Start_Mile)- CompanyCars.Lease_Mile * (CompanyCars.Excess / 100) else 0 end as overunder,
CompanyCars.Excess as ExcessRate,
CompanyCars.Company as Company
FROM [Staff Details] INNER JOIN [CompanyCarHistory] ON [Staff Details].Staffref = [CompanyCarHistory].StaffRef
INNER JOIN CompanyCars ON CompanyCars.Registration = [CompanyCarHistory].Registration
任何想法?我的SQL不是很好。
保
答案 0 :(得分:0)
我只是将你的代码放入subselect(未经测试):
SELECT *
FROM
(
select
ROW_NUMBER() OVER (PARTITION BY CompanyCars.Registration ORDER BY CompanyCars.Reg_Date DESC) AS rowid
CompanyCars.Registration as Regno,
[Staff Details].[first Name] + ' ' + [Staff Details].[Last Name] as Driver,
CompanyCars.Car_Type as VehicleType,
CompanyCars.Reg_Date as Regdate,
CompanyCars.Price as Price,
[Staff Details].[NI Number] as NInumber,
CompanyCars.End_Mile - CompanyCars.Start_Mile as UsedMiles,
CompanyCars.Lease_Mile -(CompanyCars.End_Mile - CompanyCars.Start_Mile) as ExcessMiles,
case when CompanyCars.Lease_Mile -(CompanyCars.End_Mile - CompanyCars.Start_Mile) < 0 and CompanyCars.Excess <> 0 then (CompanyCars.End_Mile - CompanyCars.Start_Mile)- CompanyCars.Lease_Mile * (CompanyCars.Excess / 100) else 0 end as overunder,
CompanyCars.Excess as ExcessRate,
CompanyCars.Company as Company
FROM [Staff Details] INNER JOIN [CompanyCarHistory] ON [Staff Details].Staffref = [CompanyCarHistory].StaffRef
INNER JOIN CompanyCars ON CompanyCars.Registration = [CompanyCarHistory].Registration
) as Temp
where rowid = 1