按别名分组

时间:2011-05-23 14:16:53

标签: sql sql-server database database-design

SELECT COALESCE (rsu.last_name + ', ' + rsu.first_name + ' ' + rsu.middle_name + '.', rsu.last_name + ', ' + rsu.first_name)  as student_name, rsu.day_id
FROM roster_school_unattended rsu
GROUP BY student_name
ORDER BY rsu.day_id

不起作用。什么是最优雅的解决方法?

编辑:结果集应该有这样的东西

Muster, Hans | 2011-11-01
Muster, Hans | 2011-11-02
Williams, Clay | 2011-10-01
Williams, Clay | 2011-10-02

首先将名称分组,然后对每个名称进行日期排序。

5 个答案:

答案 0 :(得分:2)

进行子选择可以避免输入两次:

select t.student_name, t.day_id
from (
  select COALESCE (rsu.last_name + ', ' + rsu.first_name + ' ' + rsu.middle_name + '.', rsu.last_name + ', ' + rsu.first_name) as student_name, 
    rsu.day_id
  from roster_school_unattended rsu ) t
group by t.student_name
order by t.day_id

但是你仍然遇到day_id的问题 - 它没有包含在你的分组子句中,因此如果不使用聚合(例如MAX),你将无法选择它。

答案 1 :(得分:1)

您可以使用子查询:

select student_name, day_id
from (SELECT COALESCE (rsu.last_name + ', ' + rsu.first_name + ' ' + rsu.middle_name + '.', rsu.last_name + ', ' + rsu.first_name)  as student_name, rsu.day_id
FROM roster_school_unattended rsu
) as rows
GROUP BY student_name
ORDER BY day_id

答案 2 :(得分:0)

编辑:全部内容已被替换,因为最近对该问题的修改显示不需要GROUP BY ...


对'优雅'没有任何改变......

SELECT
  rsu.last_name + ', ' + rsu.first_name + COALESCE (' ' + rsu.middle_name + '.', '') as student_name,
  rsu.day_id
FROM
  roster_school_unattended  AS [rsu]
ORDER BY
  rsu.last_name + ', ' + rsu.first_name + COALESCE (' ' + rsu.middle_name + '.', ''),
  rsu.day_id


'优雅'的可能变化......

WITH formatted_rsu AS
(
  SELECT rsu.last_name + ', ' + rsu.first_name + COALESCE (' ' + rsu.middle_name + '.', '') as student_name, rsu.day_id
  FROM   roster_school_unattended  AS [rsu]
)
SELECT   student_name, day_id
FROM     formatted_rus
ORDER BY student_name, day_id


另一种可能使用APPLY ...

SELECT      formatted_rsu.student_name, rsu.day_id
FROM        roster_school_unattended  AS [rsu]
CROSS APPLY (SELECT rsu.last_name + ', ' + rsu.first_name + COALESCE (' ' + rsu.middle_name + '.', '') as student_name) AS [formatted_rsu]
ORDER BY    formatted_rsu.student_name, rsu.day_id

答案 3 :(得分:0)

CROSS APPLY是您对非窗口表达式别名的朋友:

SELECT this.student_name, MAX(rsu.day_id) AS day_id
FROM roster_school_unattended rsu
CROSS APPLY (
  SELECT COALESCE (
      rsu.last_name+', '+rsu.first_name+' '+rsu.middle_name+'.'
    , rsu.last_name+', '+rsu.first_name
    )  AS student_name
  ) this
GROUP BY this.student_name
ORDER BY this.student_name, MAX(rsu.day_id)

(假定SQL2005及以上版本)。

答案 4 :(得分:0)

我会选择:

SELECT
    rsu.last_name
    + ', ' + rsu.first_name
    + COALESCE ( ' ' + rsu.middle_name + '.'
               , ''
               )
    AS student_name
  , rsu.day_id
FROM
    roster_school_unattended AS rsu
ORDER BY
    rsu.last_name
  , rsu.first_name
  , rsu.middle_name
  , rsu.day_id