mariadb 如何将子查询作为结果查询中的列?

xcitsw88  于 2023-03-23  发布在  其他
关注(0)|答案(2)|浏览(152)

staff表:

ID  Position Name
-----------------
1   doctor   Joe
2   nurse    Frederica
3   doctor   Mark
4   doctor   James
5   doctor   Ema
6   nurse    Dominica
7   nurse    Anna

如何使结果查询看起来像这样(?):

doctors  nurses
---------------
Joe      Frederica
Mark     Dominica
James    Anna
Ema

我试过这样的方法:

SELECT
(SELECT staff.`Name` FROM staff WHERE staff.Position = 'doctor') AS Doctors;
(SELECT staff.`Name` FROM staff WHERE staff.Position = 'nurse') AS Nurses;

但正如我所料,它不起作用。我对SQL语法的知识有限,很难在谷歌上找到这个特定问题的解决方案。
非常感谢

zazmityj

zazmityj1#

如果你真的想要这个 * 精确 * 的输出,我们可以在MySQL 8+上使用ROW_NUMBER()实现它:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Position ORDER BY ID) rn
    FROM yourTable
)

SELECT
    MAX(CASE WHEN Position = 'doctor' THEN Name END) AS doctors,
    MAX(CASE WHEN Position = 'nurse'  THEN Name END) AS nurses
FROM cte
GROUP BY rn
ORDER BY rn;
zi8p0yeb

zi8p0yeb2#

这对于SQL语法来说有点复杂。你可以从SQL窗口函数中获得帮助,例如Over()和Row_Number()。我按照你的描述创建了一个表,当我测试下面的SQL查询时,我得到了你需要的相同结果。
这是我作为工作人员的样表
下面是查询:

Select *
  From ( Select Max(Case When position = 'doctor' Then name End ) As doctors, 
                   Max(Case When position = 'nurse' Then name End ) As nurses
           From (Select Row_Number() Over(Partition By position Order By id ) As rn, 
                        position, 
                        name
                   From staff) t
          Group By rn
       )
 Order By doctors Desc Nulls Last, 
          nurses Desc Nulls Last;

P.S.我对MariaDB细节的了解比较少,我是根据我的SQL知识写的答案。

相关问题