使用Group By子句时出错

时间:2012-09-17 20:17:14

标签: sql group-by

我收到sql server错误“文本ntext和图像数据类型无法比较或排序,除非在执行时使用为null或类似”

SELECT r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A],
       CONVERT(varchar(100), t.Time) + '  To ' + CONVERT(varchar(100), h.Time) AS Timing
  FROM table_roaster_time_table AS r
       INNER JOIN table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId
       INNER JOIN table_user AS u ON r.user_id = u.user_id
       INNER JOIN table_labs AS l ON r.lab_id = l.lab_id
       INNER JOIN table_time2 AS h ON r.timeId2 = h.timeId2
 GROUP BY r.Shift, l.lab_title, u.user_name

不知道是什么问题。我也使用了聚合函数,仅用于形式,但它不起作用。

1 个答案:

答案 0 :(得分:2)

我猜您的r.Shift列是textntext类型。因此,它无法在group by

中使用

一个选项可能是在可疑列上使用CAST,但您可能会丢失数据。例如:

SELECT        r.Shift, l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100),     t.Time) + '  To ' + CONVERT(varchar(100), h.Time) AS Timing
FROM            table_roaster_time_table AS r INNER JOIN
                     table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
                     table_user AS u ON r.user_id = u.user_id INNER JOIN
                     table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
                     table_time2 AS h ON r.timeId2 = h.timeId2
GROUP BY CAST(r.Shift as varchar(max), l.lab_title, u.user_name

您还可以查看没有text列的数据查询,然后执行第二次查询以获取缺少的列。例如:

with temp as
(
    SELECT        l.lab_title AS [Assigned Lab], u.user_name AS [L/A], CONVERT(varchar(100),     t.Time) + '  To ' + CONVERT(varchar(100), h.Time) AS Timing
    FROM            table_roaster_time_table AS r INNER JOIN
                         table_time AS t ON r.timeId = t.timeId AND r.timeId = t.timeId INNER JOIN
                         table_user AS u ON r.user_id = u.user_id INNER JOIN
                         table_labs AS l ON r.lab_id = l.lab_id INNER JOIN
                         table_time2 AS h ON r.timeId2 = h.timeId2
    GROUP BY l.lab_title, u.user_name
)
SELECT   r.Shift, t.lab_title AS [Assigned Lab], t.user_name AS [L/A] --etc
 FROM            table_roaster_time_table AS r 
 INNER JOIN temp as t
on  r.id = t.id --or whatver

此外,这个SQL似乎没必要:

r.timeId = t.timeId AND r.timeId = t.timeId