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

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

我想根据加入日期从学生集合中获取唯一记录[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
mbzjlibv

mbzjlibv1#

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

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

w6lpcovy2#

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

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

qxgroojn3#

下面是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

相关问题