获取一个字段的唯一记录,并通过另一个字段与order合并

r1zk6ea1  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(336)

我想根据加入日期从学生集合中获取唯一记录[studentname]
示例:student[tablename]

studentName     joiningDate
Rosy             2018-06-25
Meera            2018-07-20                  
Rosy             2018-06-20

我尝试了下面的查询,但它不起作用。
按joiningdate从学生顺序中选择distinct(studentname)
我想要这样的结果,

studentName     joiningDate
Rosy             2018-06-25
Meera            2018-07-20
iyr7buue

iyr7buue1#

你应该试试 GROUP BY 相反,像这样:

SELECT studentName, MIN(joiningDate)
FROM student
GROUP BY studentName
sulc1iza

sulc1iza2#

下面是bigquery标准sql,适用于该表中任意数量的附加字段,不更改查询


# standardSQL

SELECT AS VALUE ARRAY_AGG(t ORDER BY joiningDate DESC LIMIT 1)[OFFSET(0)]
FROM `project.dataset.student` t
GROUP BY studentName

您可以使用问题中的虚拟数据测试、玩上面的游戏:


# standardSQL

WITH `project.dataset.student` AS (
  SELECT 'Rosy'studentName, '2018-06-25' joiningDate UNION ALL
  SELECT 'Meera', '2018-07-20' UNION ALL                  
  SELECT 'Rosy', '2018-06-20' 
) 
SELECT AS VALUE ARRAY_AGG(t ORDER BY joiningDate LIMIT 1)[OFFSET(0)]
FROM `project.dataset.student` t
GROUP BY studentName

有结果的

Row studentName joiningDate  
1   Rosy        2018-06-25   
2   Meera       2018-07-20
qmb5sa22

qmb5sa223#

你可以用 Group ByMax() 聚合函数(获取最近加入的日期)。请尝试以下查询:

SELECT studentName, 
       MAX(joiningDate) AS joiningDate
FROM student 
GROUP BY studentName
ORDER BY joiningDate ASC

相关问题