我的要求就像从sql中选择前5行,如果它只包含2行,那么默认情况下它会在剩下的3行中显示一些文字说“无数据”。所有条件都一样。
对于选择前5行,但它只包含3行,则查询将返回
ROW1
行2
ROW3
没有数据
没有数据
答案 0 :(得分:5)
请尝试:
select top 5 Col
from(
select 0 srt, Col from YourTable
union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col union all
select 1 srt, 'No Data' Col
)x
order by srt
答案 1 :(得分:0)
这将更加动态
declare @t TABLE (id int,TerminalID varchar(15))
declare @top int
set @top = 5
declare @c int --Holds Total
set @c = 0
while (@c < @top) begin
insert into @t (id, TerminalID) values (@c, 'No Data')
set @c = @c + 1
end
select top 5 * from
(
select top 5 TerminalID from AccessLog-- [where colo0 = ???]
union all
select TerminalID from @t
) x
答案 2 :(得分:0)
/* assuming the column width is 8 characters and datatype is varchar */
DECLARE @NoDataTable AS TABLE(column1 VARCHAR(8))
DECLARE @i AS INT
SET @i = 0
WHILE(@i<5)
BEGIN
insert into @NoDataTable (column1)
values('No Data');
set @i = @i+1
end
select top 5 *
from
(
select column1 from TestTable
union all
select column1 from @NoDataTable
) as T
答案 3 :(得分:0)
WITH cte AS
(
SELECT YourColumn FROM YourTable
UNION ALL
SELECT TOP 5 NULL FROM YourTable
)
SELECT TOP 5 COALESCE(YourColumn, 'No Data')
FROM cte