SQL Server向结果中添加X行,使其始终等于5行输出

时间:2018-10-24 10:29:38

标签: sql sql-server sql-server-2012

我有代码可以返回任何给定ID(包括给定ID)的最后5个结果。我想要的是,如果没有先前的值等于5,则分别返回带有单词none00的额外行。

因此,如果代码返回3个结果,则产生2条额外的行,如果代码返回4个结果,则产生1条额外的行。

当前代码:(aaa.FS01 = '12345')只是ID的示例

SELECT aaa.FS01,
CAST(COUNT(distinct bbb.MG) AS FLOAT)/ convert(varchar(10), DATEDIFF(second ,MIN(TP), MAX(TP))/3600.0) TPDIFF,
22 TAG
FROM TableA aaa
INNER JOIN TableB bbb ON bbb.tpl = aaa.FS01 OR bbb.fpl = aaa.FS01
INNER JOIN TableC ccc ON ccc.id = aaa.FS01
INNER JOIN TableD ddd ON aaa.VG = ddd.gkey
WHERE aaa.FS01 IN (
SELECT TOP 5 ccc.id 
FROM TableA aaa
INNER JOIN TableC ccc ON ccc.id = aaa.FS01
INNER JOIN TableD v ON aaa.VG = ddd.gkey
WHERE ddd.name = (SELECT ddd.name FROM TableA aaa
INNER JOIN TableD v ON aaa.VG = ddd.gkey WHERE aaa.FS01 = '12345')
ORDER BY ccc.ata DESC) 
GROUP BY aaa.FS01, ccc.ata
ORDER BY ccc.ata DESC

当前输出(对于仅返回3个值的FS01):

FS01    TPDIFF   TAG
12345   30       22
22222   50       22
45122   90       22

预期输出(对于仅返回3个值的FS01):

FS01    TPDIFF   TAG
12345   30       22
22222   50       22
45122   90       22
none    00       22
none    00       22

当前输出(对于仅返回1个值的FS01):

FS01    TPDIFF   TAG
74133   30       22

预期输出(对于仅返回1个值的FS01):

FS01    TPDIFF   TAG
74133   80       22
none    00       22
none    00       22
none    00       22
none    00       22

2 个答案:

答案 0 :(得分:2)

您可以通过一个查询来做到这一点:

with t as (<your query here>),
     nones as (
      select 'none' as FS01, '00' as TPDIFF, '22' as TAG
      from (values (1), (2), (3), (4), (5))
     )
select top (5) tn.FS01, tn.TPDIFF, tn.TAG
from ((select t.* from t) union all
      nones
     ) tn
order by (case when FS01 = 'none' then 1 else 2 end) as asc;

答案 1 :(得分:1)

我会这样声明一个表变量。然后使用一会儿来追加空行。

类似这样的东西:

DECLARE @tbl AS TABLE(FS01 text, TPDIFF text, TAG Text);
INSERT INTO @tbl (FS01, TPDIFF, TAG) 

--your select statement (copied)
SELECT aaa.FS01,
CAST(COUNT(distinct bbb.MG) AS FLOAT)/ convert(varchar(10), DATEDIFF(second ,MIN(TP), MAX(TP))/3600.0) TPDIFF,
22 TAG
FROM TableA aaa
INNER JOIN TableB bbb ON bbb.tpl = aaa.FS01 OR bbb.fpl = aaa.FS01
INNER JOIN TableC ccc ON ccc.id = aaa.FS01
INNER JOIN TableD ddd ON aaa.VG = ddd.gkey
WHERE aaa.FS01 IN (
SELECT TOP 5 ccc.id 
FROM TableA aaa
INNER JOIN TableC ccc ON ccc.id = aaa.FS01
INNER JOIN TableD v ON aaa.VG = ddd.gkey
WHERE ddd.name = (SELECT ddd.name FROM TableA aaa
INNER JOIN TableD v ON aaa.VG = ddd.gkey WHERE aaa.FS01 = '12345')
ORDER BY ccc.ata DESC) 
GROUP BY aaa.FS01, ccc.ata
ORDER BY ccc.ata DESC


declare @cnt as int;
SELECT @cnt = count(*) from @tbl

while @cnt < 5
    BEGIN
        insert into @tbl (FS01, TPDIFF, TAG) VALUES('none', '00', '22');
        select @cnt = @cnt+1;
    end

select top 5 * from @tbl;