Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

# 第9回オフラインリアルタイムどう書くの問題をSQLで解く

http://nabetani.sakura.ne.jp/hena/ord9busfare/
テストに使用したDBはMySQLです。

まず問題を入れるテーブル作成。

``````DROP TABLE IF EXISTS charge;
CREATE TABLE charge(charge INT,expect INT);
DROP TABLE IF EXISTS PASSENGERS;
CREATE TABLE passengers(age CHAR(1),type CHAR(1));
``````

``````INSERT INTO charge VALUES(210,170);
INSERT INTO passengers VALUES('C','n');
INSERT INTO passengers VALUES('I','n');
INSERT INTO passengers VALUES('I','w');
INSERT INTO passengers VALUES('A','p');
INSERT INTO passengers VALUES('I','w');
``````

そして解く。
OFFSET指定でサブクエリが使えたらテンポラリテーブルを作らなくてすんだのに・・。

``````CREATE TEMPORARY TABLE wk(id INT PRIMARY KEY AUTO_INCREMENT,charge INT)
SELECT * FROM(
SELECT TRUNCATE(charge/20+0.9,0)*10 AS charge FROM passengers JOIN charge WHERE age='I' AND type='n'
UNION ALL
SELECT TRUNCATE((TRUNCATE(charge/20+0.9,0)*10)/20+0.9,0)*10 AS charge FROM passengers JOIN charge WHERE age='I' AND type='w'
) AS wk ORDER BY charge DESC;

SELECT SUM(charge) AS charge, SUM(charge) = (SELECT expect FROM charge) AS result FROM(
SELECT SUM(charge) AS charge FROM passengers JOIN charge WHERE age='A' AND type='n'
UNION ALL
SELECT SUM(TRUNCATE(charge/20+0.9,0)*10) AS charge FROM passengers JOIN charge WHERE age='A' AND type='w'
UNION ALL
SELECT SUM(TRUNCATE(charge/20+0.9,0)*10) AS charge FROM passengers JOIN charge WHERE age='C' AND type='n'
UNION ALL
SELECT SUM(TRUNCATE((TRUNCATE(charge/20+0.9,0)*10)/20+0.9,0)*10) AS charge FROM passengers JOIN charge WHERE age='C' AND type='w'
UNION ALL
SELECT SUM(charge) AS charge FROM wk WHERE id > (SELECT COUNT(*)*2 FROM passengers WHERE age='A')
) AS total;
``````
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?