返回介绍

solution / 0600-0699 / 0618.Students Report By Geography / README_EN

发布于 2024-06-17 01:03:36 字数 2488 浏览 0 评论 0 收藏 0

618. Students Report By Geography

中文文档

Description

Table: Student

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| name    | varchar |
| continent   | varchar |
+-------------+---------+
This table may contain duplicate rows.
Each row of this table indicates the name of a student and the continent they came from.

 

A school has students from Asia, Europe, and America.

Write a solution to pivot the continent column in the Student table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia, and Europe, respectively.

The test cases are generated so that the student number from America is not less than either Asia or Europe.

The result format is in the following example.

 

Example 1:

Input: 
Student table:
+--------+-----------+
| name   | continent |
+--------+-----------+
| Jane   | America   |
| Pascal | Europe  |
| Xi   | Asia    |
| Jack   | America   |
+--------+-----------+
Output: 
+---------+------+--------+
| America | Asia | Europe |
+---------+------+--------+
| Jack  | Xi   | Pascal |
| Jane  | null | null   |
+---------+------+--------+

 

Follow up: If it is unknown which continent has the most students, could you write a solution to generate the student report?

Solutions

Solution 1

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      *,
      ROW_NUMBER() OVER (
        PARTITION BY continent
        ORDER BY name
      ) AS rk
    FROM Student
  )
SELECT
  MAX(IF(continent = 'America', name, NULL)) AS 'America',
  MAX(IF(continent = 'Asia', name, NULL)) AS 'Asia',
  MAX(IF(continent = 'Europe', name, NULL)) AS 'Europe'
FROM T
GROUP BY rk;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文