gpt4 book ai didi

mysql - 选择少数列的不同值和少数列的多个值

转载 作者:行者123 更新时间:2023-11-29 15:36:09 25 4
gpt4 key购买 nike

我必须沿着同一表的几列的多个值选择几列的不同值。我的 table 是这样的

enter image description here

当像这样显示此表时,我想选择first_name和last_name列的不同值以及主题列的所有值

enter image description here

是否可以显示名字和姓氏的不同值?

Select DISTINCT `first_name` , `last_name` from table1

最佳答案

我尝试过使用分区子句来处理给定的场景。请检查下面的示例代码片段。它有效。

CREATE TABLE #Student                                                                  
(
first_name VARCHAR(100),
last_name VARCHAR(100),
[subject] VARCHAR(100)
)

INSERT INTO #Student (first_name, last_name, [subject]) VALUES ('a','b','maths')
INSERT INTO #Student (first_name, last_name, [subject]) VALUES ('a','b','science')
INSERT INTO #Student (first_name, last_name, [subject]) VALUES ('e','f','bio')
INSERT INTO #Student (first_name, last_name, [subject]) VALUES ('e','f','eng')


SELECT CASE WHEN reportTbl.RowNo = 1 THEN first_name ELSE '' END as first_name,
CASE WHEN reportTbl.RowNo = 1 THEN last_name ELSE '' END as last_name,
[Subject] FROM
(
SELECT first_name, last_name, [Subject],
ROW_NUMBER() OVER (PARTITION BY first_name, last_name ORDER BY subject) RowNo
FROM #Student
)
reportTbl

Actual Table after added RowNo coloumn with partition by clause

enter image description here

Below is the final output of the query

enter image description here

关于mysql - 选择少数列的不同值和少数列的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58217053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com