34,837
社区成员




select bus.bus_name, cast(tempbus.total_num*100/bus.bus_seatcount as varchar(50))+'%' 上座率
from table_bus bus join
(
select b.bus_name, SUM(b.num) as total_num
from
(
select t.bus_name, t.ticket_date, COUNT(t.bus_name) as num from
(
select bus_name, ticket_date from table_bus a
left join table_ticket b
on a.bus_id = b.ticket_bus_id
where ticket_date between '2013-2-1' and '2013-3-4'
)t
group by t.bus_name, t.ticket_date
)b
group by b.bus_name
) tempbus
on bus.bus_name = tempbus.bus_name
select bus_name
,convert(varchar,convert(decimal(10,2),sum(ISNULL(b.num,0))*100.0/(a.bus_seatcount*DATEDIFF(d,'2013-03-01','2013-03-04'))))+'%'
from table_bus a outer apply
(select MAX(Ticket_SeatNo)num from table_ticket where a.Bus_Id=Ticket_Bus group by date)b
group by bus_name,bus_seatcount
order by bus_name
/*
bus_name (无列名)
bus01 4.44%
bus02 8.33%
bus03 2.50%
bus04 0.95%
bus05 0.00%
*/
insert into table_bus (bus_name, bus_seatcount) values ('bus01', 30);
insert into table_bus (bus_name, bus_seatcount) values ('bus02', 20);
insert into table_bus (bus_name, bus_seatcount) values ('bus03', 40);
insert into table_bus (bus_name, bus_seatcount) values ('bus04', 35);
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(1,1,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(1,2,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(1,1,'2013-3-2');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(1,2,'2013-3-2');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(2,1,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(2,2,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(2,1,'2013-3-2');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(2,2,'2013-3-2');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(2,1,'2013-3-3');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(3,1,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(3,2,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(3,3,'2013-3-1');
insert into table_ticket(ticket_bus_id, ticket_seat_no, date) values(4,1,'2013-3-3');
select bus.bus_name, b.ticket_date, cast(b.num*100/bus.bus_seatcount as varchar(50))+'%' 上座率
from table_bus bus join
(
select t.bus_name, t.ticket_date, COUNT(t.bus_name) as num from
(
select bus_name, ticket_date from table_bus a
left join table_ticket b
on a.bus_id = b.ticket_bus_id
where ticket_date between '2013-2-1' and '2013-3-4'
)t
group by t.bus_name, t.ticket_date
)b
on bus.bus_name = b.bus_name
order by b.ticket_date
bus_name ticket_date 上座率
bus01 2013-03-01 6%
bus02 2013-03-01 10%
bus03 2013-03-01 7%
bus01 2013-03-02 6%
bus02 2013-03-02 10%
bus02 2013-03-03 5%
bus04 2013-03-03 2%