简体   繁体   English

如何从选择查询中选择 7 行或更多行? 即使表返回少于 7 行

[英]How to select 7 rows or more from select query? even if table is returning less than 7 rows

I want a script that gives me an exact 7 rows.我想要一个给我精确 7 行的脚本。 For example, if my table returns only 2 rows then we have to add another 5 rows with all columns contains a null value.例如,如果我的表只返回 2 行,那么我们必须添加另外 5 行,所有列都包含空值。 But if the table returns more than 7 rows then select all returned rows.但如果表返回超过 7 行,则选择所有返回的行。 Please Help!请帮忙!

Try this below logic-试试这个下面的逻辑 -

Demo Here for less than 7 rows Demo Here少于 7 行

Demo Here for more than 7 rows 在这里演示超过 7 行

WITH CTE(rn,id,name)
as
(
  select 1, null, null union all
  select 2, null, null union all
  select 3, null, null union all
  select 4, null, null union all
  select 5, null, null union all
  select 6, null, null union all
  select 7, null, null
)


SELECT a.id,a.name 
FROM
(
    select 
    ROW_NUMBER() OVER(order by id) rn,id,name
    from your_table
)A
full join CTE ON A.rn = cte.rn

The query is below:查询如下:

with cte1 as (
  select col1,col2,...,row_number() over(order by col1) as rn,count(*) over() as cnt from table1
  union all select null,null,...,rn,cnt+1 from cte1 where rn=1 and cnt<7
)
select col1,col2,... from cte1;

dbfiddle 数据库小提琴

I would phrase this as:我会这样表述:

With the FULL JOIN method, you need to list the columns you want or get seqnum in the result set:使用FULL JOIN方法,你需要在结果集中列出你想要的列或获取seqnum

SELECT t.*  -- or list the columns to avoid seqnum
FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as seqnum
      FROM t
     ) t FULL JOIN
     (VALUES (1), (2), (3), (4), (5), (6), (7)) v(n)
     ON seqnum = v.n;

An alternative that does not require listing all the columns is:不需要列出所有列的替代方法是:

select t.*
from t
union all
select t.*
from (values (1), (2), (3), (4), (5), (6), (7)) v(n) left join
     t
     on 1 = 0   -- never true
where v.n <= 7 - (select count(*) from t)

Create a dummy table with 2 Fields创建一个包含 2 个字段的虚拟表

CREATE TABLE dummy (
  id INT NOT NULL,
  NullVals VARCHAR(5) DEFAULT NULL,
  PRIMARY KEY (id));

Now insert these values to this table:现在将这些值插入到该表中:

INSERT INTO dummy (id, NullVals) VALUES 
  (1, NULL),
  (2, NULL),
  (3, NULL),
  (4, NULL),
  (5, NULL),
  (6, NULL),
  (7, NULL);

run your query as follows:运行您的查询如下:

Select acolumn from abc_table where acolumn like 'something'

union All

select NullVals from dummy
where id <= 7-(select count(*) from abc_table where acolumn like 'something');

Also you can replace the dummy table with CTE您也可以用 CTE 替换虚拟表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM