表:Logs
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | num | varchar | +-------------+---------+ id 是这个表的主键。
编写一个 SQL 查询,查找所有至少连续出现三次的数字。
返回的结果表中的数据可以按 任意顺序 排列。
题意分析:题意易懂,就是查询所有连续出现三次的非重复数字,最简单直接的方法,就是判断每三个连续的数字是否相等,可以通过递增的id数进行操纵。
SELECT DISTINCT l.Num ConsecutiveNums FROM Logs l WHERE l.Num = (SELECT Num FROM Logs where Id = l.Id - 1) AND l.Num = (SELECT Num FROM Logs where Id = l.Id - 2)
Stocks 表:
+---------------+---------+ | Column Name | Type | +---------------+---------+ | stock_name | varchar | | operation | enum | | operation_day | int | | price | int | +---------------+---------+ (stock_name, day) 是这张表的主键 operation 列使用的是一种枚举类型,包括:('Sell','Buy') 此表的每一行代表了名为 stock_name 的某支股票在 operation_day 这一天的操作价格。 保证股票的每次'Sell'操作前,都有相应的'Buy'操作。
编写一个SQL查询来报告每支股票的资本损益。
股票的资本损益是一次或多次买卖股票后的全部收益或损失。
以任意顺序返回结果即可。
题意理解:简单易懂,每一个名字对应的buy的sell的操作的钱总数减去buy的钱总数,使用sum操作即可。
# Write your MySQL query statement below SELECT DISTINCT s.stock_name, sum(if(operation='Buy', -price, price)) capital_gain_loss FROM Stocks s GROUP BY stock_name
这里的if函数用的相当精彩。
患者信息表: Patients
+--------------+---------+ | Column Name | Type | +--------------+---------+ | patient_id | int | | patient_name | varchar | | conditions | varchar | +--------------+---------+ patient_id (患者 ID)是该表的主键。 'conditions' (疾病)包含 0 个或以上的疾病代码,以空格分隔。 这个表包含医院中患者的信息。
写一条 SQL 语句,查询患有 I 类糖尿病的患者 ID (patient_id)、患者姓名(patient_name)以及其患有的所有疾病代码(conditions)。I 类糖尿病的代码总是包含前缀 DIAB1 。
按 任意顺序 返回结果表。
题意分析:非常简单,只要通过正则表达式判断即可。
SELECT p.patient_id,p.patient_name,p.conditions FROM Patients p WHERE conditions like 'DIAB1%' OR conditions like '% DIAB1%'
表 Activities:
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | sell_date | date | | product | varchar | +-------------+---------+ 此表没有主键,它可能包含重复项。 此表的每一行都包含产品名称和在市场上销售的日期。
编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。 每个日期的销售产品名称应按词典序排列。 返回按 sell_date 排序的结果表。 查询结果格式如下例所示。
select sell_date, COUNT(DISTINCT product)AS 'num_sold', GROUP_CONCAT( DISTINCT product ORDER by product asc SEPARATOR ',' )AS products from Activities GROUP by sell_date ORDER by sell_date;
这里用了一个关键字:group_concat,用于将制定数据连接成集合。
表:Products
+-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | store1 | int | | store2 | int | | store3 | int | +-------------+---------+ 这张表的主键是product_id(产品Id)。 每行存储了这一产品在不同商店store1, store2, store3的价格。 如果这一产品在商店里没有出售,则值将为null。
题意分析:列传行,使用unionall
select product_id,'store1' store, store1 price from Products where store1 is not null union all select product_id,'store2', store2 from Products where store2 is not null union all select product_id,'store3', store3 from Products where store3 is not null
ps:行转列一般用sum + if
SELECT product_id, SUM(IF(store = 'store1', price, NULL)) 'store1', SUM(IF(store = 'store2', price, NULL)) 'store2', SUM(IF(store = 'store3', price, NULL)) 'store3' FROM Products1 GROUP BY product_id ;