【问题标题】:How to get multiple records combined to one using row number?如何使用行号将多条记录合并为一条?
【发布时间】:2017-09-19 17:22:47
【问题描述】:

如何让多个警报记录(每个学生最多 10 个)显示在每个学生的一条记录上?我正在尝试使用行号对记录进行编号,然后将它们放在输出中,但是由于交叉应用语句中“where”参数的语法错误不正确,我编写的代码不起作用。我尝试了多种方法来完成我所需要的,但无法克服错误。请帮忙。

select 
sd.[student_number],
a.[health_alert],
a.[comments],
b.[health_alert],
b.[comments]

from student_enrollmentcube as se,
   student_demographicscube as sd

cross apply (select  a.[health_alert], a.[comments], (select row_number() 
 over (partition by a.[student_id] order by a.[student_id]) as r1 from 
   ar_student_health_alerts) a)  where a.[student_id] = sd.[student_id] and 
    r1 = 1)
cross apply (select  b.[health_alert], b.[comments], (select row_number() 
 over (partition by b.[student_id] order by b.[student_id]) as r2 from 
  ar_student_health_alerts) b)  where b.[student_id] = sd.[student_id] and 
   r2 = 2)

where se.student_id = sd.student_id and
     se.enrollment_status= 'active' and
     se.[current_academic_year] = 'y'

【问题讨论】:

  • 这与 SQL 有关吗?如果是这样,请适当地标记。
  • 请同时包含准确的错误信息

标签: sql-server row-number cross-apply


【解决方案1】:

您的语法存在多个问题,包括嵌入在其他不完整选择语句中的不完整选择语句,甚至是表别名与文字值的比较。

我建议你把它分成几块。您的交叉应用语句需要能够独立运行,但对外部表的引用除外。

换句话说,让这个工作:

(select  a.[health_alert], a.[comments], (select row_number() 
 over (partition by a.[student_id] order by a.[student_id]) as r1 from 
   ar_student_health_alerts) a)  where a.[student_id] = sd.[student_id] and 
    r1 = 1)

在您尝试在交叉应用中使用它之前。

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多