https://leetcode.com/problems/rearrange-products-table/description/
select product_id, 'store1' as store, store1 as price from Products where store1 is not null
UNION ALL
select product_id, 'store2' as store, store2 as price from Products where store2 is not null
UNION ALL
select product_id, 'store3' as store, store3 as price from Products where store3 is not null
SQL中的“行转列”和“列转行”是两种常见的数据转换方式。下面分别通过举例说明它们的区别:
行转列是指将多行数据转换成多列,常用于把一个表中的某个字段的不同值转为表的列头。
假设有一个销售表 sales
,记录了不同月份的销售额:
销售员 | 月份 | 销售额 |
---|---|---|
张三 | 1月 | 100 |
张三 | 2月 | 200 |
李四 | 1月 | 150 |
李四 | 2月 | 250 |
我们希望将月份作为列,将销售员的销售额展示为列值。使用 行转列 进行转换。
SELECT 销售员,
MAX(CASE WHEN 月份 = '1月' THEN 销售额 END) AS '1月',
MAX(CASE WHEN 月份 = '2月' THEN 销售额 END) AS '2月'
FROM sales
GROUP BY 销售员;
结果:
销售员 | 1月 | 2月 |
---|---|---|
张三 | 100 | 200 |
李四 | 150 | 250 |
列转行是指将表中的列数据转换成行数据,通常用于将表中以列为单位的数据展开展开成多行。
继续使用上述 sales
表,假设我们将列转行为行的形式,想要从上述的“行转列”结果还原。
SELECT 销售员, 月份, 销售额
FROM (SELECT 销售员,
'1月' AS 月份,
100 AS 销售额
UNION ALL
SELECT 销售员,
'2月' AS 月份,
200 AS 销售额) AS tmp;
结果:
销售员 | 月份 | 销售额 |
---|---|---|
张三 | 1月 | 100 |
张三 | 2月 | 200 |
李四 | 1月 | 150 |
李四 | 2月 | 250 |
希望这两个例子能帮助你更好地理解行转列和列转行的区别!
https://leetcode.com/problems/calculate-special-bonus/description/
select employee_id, case when employee_id % 2 = 1 and name not like 'M%' then salary else 0 end as bonus
from Employees
order by employee_id
https://leetcode.com/problems/the-latest-login-in-2020/
select user_id, max(time_stamp)
from Logins
where YEAR(time_stamp) = 2020
group by user_id
SELECT DISTINCT user_id,
FIRST_VALUE(time_stamp)OVER(PARTITION BY user_id ORDER BY time_stamp DESC) AS last_stamp
FROM Logins
WHERE EXTRACT(Year FROM time_stamp) = 2020;
https://leetcode.com/problems/count-salary-categories/description/
SELECT 'Low Salary' AS category, SUM(CASE WHEN income < 20000 THEN 1 ELSE 0 END) AS accounts_count
FROM Accounts
UNION
SELECT 'Average Salary' category, SUM(CASE WHEN income >= 20000 AND income <= 50000 THEN 1 ELSE 0 END)
AS accounts_count
FROM Accounts
UNION
SELECT 'High Salary' category, SUM(CASE WHEN income > 50000 THEN 1 ELSE 0 END) AS accounts_count
FROM Accounts
https://leetcode.com/problems/confirmation-rate/
select s.user_id,
CASE
when action is null then 0.0
else round(sum(if(action = 'confirmed', 1, 0)) / count(action), 2)
end as confirmation_rate
from Signups s
left join confirmations c on s.user_id = c.user_id
group by s.user_id
https://leetcode.com/problems/employees-with-missing-information/description/
select employee_id from Employees where employee_id not in (select employee_id from Salaries)
UNION ALL
select employee_id from Salaries where employee_id not in (select employee_id from Employees)
order by employee_id asc