早上好。
我被要求根据轮胎更换和车辆检查做一份报告。
我在帖子的底部附上了不同的部分。
但我基本上要做的是找出轮胎在资产上的特定位置有多长时间以及轮胎何时穿上和另一轮胎取代它之间的差异等。
我不知道从哪里开始这个查询,因为我一般都是sql server的新手。
我在sql中的表是
CREATE TABLE assets_tyre_change_header
( id INT NOT NULL IDENTITY(1,1),
change_date date not null,
asset_id varchar(50) not null,
odometer_hour varchar(50),
completed tinyint,
comment text,
CONSTRAINT assets_tyre_change_pk PRIMARY KEY (id)
);
CREATE TABLE assets_tyre_change_details
( id INT NOT NULL IDENTITY(1,1),
tyre_change_id INT,
tyre_id varchar(50) not null,
wheel_position varchar(50) not null,
tread_depth int not null,
minimum_depth int not null
CONSTRAINT assets_tyre_change_detail_pk PRIMARY KEY (id)
);
create table assets_tyre_inspection_header
( id INT NOT NULL IDENTITY(1,1),
inspection_date date not null,
asset_id varchar(50) not null,
odometer_hour varchar(50),
completed tinyint,
comment text,
CONSTRAINT assets_tyre_inspection_pk PRIMARY KEY (id)
);
CREATE TABLE assets_tyre_inspection_details
( id INT NOT NULL IDENTITY(1,1),
tyre_inspection_id INT,
tyre_id varchar(50) not null,
wheel_position varchar(50) not null,
tread_depth int not null
CONSTRAINT assets_tyre_inspection_detail_pk PRIMARY KEY (id)
);
我的下一步是从这些表中提取基本详细信息作为结果表
附加sql
select * from (
(select 'change' as type,
tyre_id,
asset_id,
wheel_position,
min(convert(int,odometer_hour))as min_oh,
max(convert(int,odometer_hour))as max_oh,
min(tread_depth)as min_depth,
min(change_date) as transdate
from assetsandfuel.dbo.assets_tyre_change_details as c_details
join assetsandfuel.dbo.assets_tyre_change_header as c_header on c_header.id = c_details.tyre_change_id
group by asset_id,tyre_id,wheel_position
)
union
(select 'inspect' as type,
tyre_id,
asset_id,
wheel_position,
min(convert(int,odometer_hour))as min_oh,
max(convert(int,odometer_hour))as max_oh,
min(tread_depth)as min_depth,
min(inspection_date) as transdate
from assetsandfuel.dbo.assets_tyre_inspection_details as i_details
join assetsandfuel.dbo.assets_tyre_inspection_header as i_header on i_header.id = i_details.tyre_inspection_id
group by asset_id,tyre_id,wheel_position
)
)as report_table
order by transdate;
这导致以下记录作为表结果传递
type tyre asset position min max depth transdate
change T001 TestV 4 1489 1489 15 2016-04-01
change T002 TestV 6 1489 1489 15 2016-04-01
change F146 Forklift001 3 6900 6900 30 2016-04-02
change F147 Forklift001 2 6900 6900 30 2016-04-02
change T001 TestV 6 2800 2800 12 2016-04-08
change T002 TestV 4 2800 2800 10 2016-04-08
change T003 TestV 12 2800 2800 15 2016-04-08
inspect F146 Forklift001 3 6920 6920 27 2016-04-09
inspect F147 Forklift001 2 6920 6920 15 2016-04-09
inspect T001 TestV 6 3400 3400 9 2016-04-10
inspect T003 TestV 12 3400 3400 12 2016-04-10
change F148 Forklift001 1 6950 6950 30 2016-04-11
change F149 Forklift001 4 6950 6950 30 2016-04-11