我有查询:
select RankCode, (SELECT '' + SUBSTRING( CONVERT(VARCHAR, FromDate, 120) ,11, 6) + ' -' + SUBSTRING( CONVERT(VARCHAR, ToDate, 120), 11, 6) ) as WorkingHoursAtSea
from WorkingHoursSchedule
where SeaPortInd = 0 and watchkeepingind = 0
这是上面的结果表:
+----------+-------------------+
| RankCode | WorkingHoursAtSea |
+----------+-------------------+
| C/E | 05:00 - 07:00 |
| C/E | 01:00 - 02:00 |
| MSTR | 00:30 - 02:30 |
+----------+-------------------+
我想采取下表:
+----------+-------------------+
| RankCode | WorkingHoursAtSea |
+----------+-------------------+
| C/E | 05:00 - 07:00 |
| | 01:00 - 02:00 |
| MSTR | 00:30 - 02:30 |
+----------+-------------------+
我使用的是MS SQL SERVER 2014。
先谢谢了。 PS:我不知道如何绘制表格,所以我用图片链接显示它。
答案 0 :(得分:0)
首先,您的查询不需要嵌套SELECT
。并且,在SQL Server中,总是包含字符类型定义的长度(默认值因上下文而异,可能不够大)。所以:
select RankCode,
(substring(convert(varchar(255), FromDate, 120), 11, 6) + ' -' +
substring(convert(varchar(255), ToDate, 120), 11, 6)
) as WorkingHoursAtSea
from WorkingHoursSchedule
where SeaPortInd = 0 and watchkeepingind = 0 ;
(“255”是任意的,只是为了足够大。)
接下来,您还有另一个问题,因为SQL表和结果集本身就是无序。您需要一列来指定排序,并且您的查询没有order by
。在确定列的内容后,您可以使用lag()
或row_number()
来获取所需信息:
select RankCode,
(case when row_number() over (partition by RankCode order by ??) = 1
then (substring(convert(varchar(255), FromDate, 120), 11, 6) + ' -' +
substring(convert(varchar(255), ToDate, 120), 11, 6)
)
end) as WorkingHoursAtSea
from WorkingHoursSchedule
where SeaPortInd = 0 and watchkeepingind = 0 ;
编辑:
哦,你应该在应用层真的做那种处理。您可以在SQL中执行此操作,但ORDER BY
是必需的,因为结果集是无序的。 。 。和订购对您的结果很重要。
这是一个想法:
select (case when row_number() over (partition by RankCode order by ??) = 1
then RankCode
end) as RankCode,
(substring(convert(varchar(255), FromDate, 120), 11, 6) + ' -' +
substring(convert(varchar(255), ToDate, 120), 11, 6)
) as WorkingHoursAtSea
from WorkingHoursSchedule
where SeaPortInd = 0 and watchkeepingind = 0
order by RankCode, ??;
??
应该是相同的。您可以在两种情况下尝试FromDate desc
以获得问题中的输出。
答案 1 :(得分:0)
试试这个,
geom_line()
这与@Gordon Linoff的帖子非常相似。