gpt4 book ai didi

SQL 合并行并创建列

转载 作者:行者123 更新时间:2023-12-03 05:09:14 25 4
gpt4 key购买 nike

有时最难的事情是知道如何提出正确的问题,但我会尝试一下。
我正在尝试找出一个 SQL 语句(我在 Azure SQL 中),该语句将检索多行、组合某些列并从其他列创建新的别名列,所有这些都是针对从较大的 select 语句返回的每一行。清澈如泥?让我试着把它画出来。

    Employees    
------------
employeeID | managerID | fname
1 5 Bill
2 5 John
3 6 Mary


ClassRegistration
-----------------
employeeID | classID
1 25
2 25
1 27
1 28
2 30
1 45
1 55
2 35


Classes
----------
classID | classStartDate
25 7/1/2014
27 7/14/2014
28 7/28/2014
30 7/11/2014
35 8/1/2014
45 8/1/2014

我需要返回的是这样的表格:

Employee fname  |  Last Class |  Upcoming Class 
Bill 27 28
John 30 35

所以我需要类似的东西:选择*员工WHERE managerID = 5。
然后使用具有指定 managerID 的所有员工的结果集,为返回的每个员工返回一行中的最后一个类(class)和下一个类(class)。
此外,员工可能有也可能没有最后一个类和/或即将到来的类(class)。

我见过许多不同的方法来使用临时表或与 GROUP BY 组合等来迭代行。但我似乎无法理解我需要什么组合。

最佳答案

更好的解决方案...使用over子句...

SELECT DISTINCT E.empId, E.managerid, e.fname,    
                Max(lastclass.classStartDate) over(partition by e.empId) as lastClass,
            Min(nextClass.classStartDate) over(partition by e.empId) as nextClass
FROM [T_employees] E
INNER JOIN T_ClassRegistration CR on E.empId = CR.empid
LEFT JOIN T_Classes lastclass on CR.classid = lastclass.classid 
and lastclass.classStartDate <= getdate()
LEFT JOIN T_Classes nextClass on CR.classid = nextClass.classid 
and nextClass.classStartDate> getdate()
WHERE managerId = 5

 

关于SQL 合并行并创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24781440/

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