-
Notifications
You must be signed in to change notification settings - Fork 1
/
0007_select_sample.sql
135 lines (134 loc) · 2.48 KB
/
0007_select_sample.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* テーブル1個からデータを取得する */
-- 端末データを全部取得
SELECT
*
FROM device
;
-- <モデル名>だけ取得
SELECT
model_name
FROM device
;
-- OSごとの端末数
SELECT
os_id
,COUNT(*) AS 端末数
FROM device
GROUP BY
os_id
;
-- iOS端末だけ取得
SELECT
*
FROM device
WHERE
os_id = 2
;
-- モデル名に'xperia'が含まれる端末を取得
SELECT
*
FROM device
WHERE
model_name LIKE '%xperia%'
;
-- 返却済の貸出データ
SELECT
*
FROM lend
WHERE
return_flag = 1
;
-- 当日もしくは翌日に返却された貸出データ
SELECT
*
FROM lend
WHERE
return_flag = 1
AND (
DATEDIFF(return_datetime, lend_datetime) <= 1
)
;
-- 端末ごとの貸出回数
SELECT
device_id
,COUNT(*)
FROM lend
GROUP BY
device_id
;
-- 3回以上貸し出された端末
SELECT
device_id
,COUNT(*)
FROM lend
GROUP BY
device_id
HAVING
COUNT(*) >= 3
;
/* 複数のテーブルからデータを取得する */
-- 端末のモデル名、OS名、通信キャリア名を取得
SELECT
D.device_id
,D.model_name
,OM.os_name
,IFNULL(CM.carrier_name, '(キャリア契約なし)') AS carrier_name
FROM device AS D
INNER JOIN os_master AS OM
ON D.os_id = OM.os_id
LEFT OUTER JOIN telecom_carrier_master AS CM
ON D.carrier_id = CM.carrier_id
ORDER BY
D.device_id
;
-- 貸出中の端末
SELECT
D.device_id
,D.model_name
FROM device_lend_status AS S
INNER JOIN device AS D
ON S.device_id = D.device_id
WHERE
S.lended = 1
;
-- 貸出状態を表示
SELECT
D.device_id
,D.model_name
,CASE WHEN S.lended = 1 THEN '■貸出中' ELSE '□貸出可能' END AS '貸出状況'
FROM device_lend_status AS S
INNER JOIN device AS D
ON S.device_id = D.device_id
;
-- 返却していない端末をもっている利用者
SELECT
CONCAT(U.last_name, ' ', U.first_name) AS user_name
FROM user AS U
WHERE
EXISTS (
SELECT
*
FROM lend
WHERE
return_flag = 0
AND user_id = U.user_id
)
;
-- 返却していない端末をもっている利用者と、その利用者がもっている端末数
SELECT
L.user_id
,L.device_count
,CONCAT(U.last_name, ' ', U.first_name) AS user_name
FROM (
SELECT
user_id
,COUNT(device_id) AS device_count
FROM lend
WHERE
return_flag = 0
GROUP BY
user_id
) AS L
INNER JOIN user AS U
ON L.user_id = U.user_id
;