我有这张桌子,说学生。如果表中有2个学生,并且结果集给出2行,那么无论我说“ type,symbol,price,quantity,expirydate,strikeprice,amendtime,id,parentid
T,ICICIBANK,1000,100,20121210,120,20121209103030,1234,0
T,AXISBANK,1000,100,20121210,120,20121209103031,1235,0
T,SBIBANK,1000,100,20121210,120,20121209103032,1236,0
P,ICICIBANK,1100,100,20121210,120,20121209103030,1237,1234
P,AXISBANK,1000,100,20121210,120,20121209103031,1238,1235
T,ICICIBANK,1000,100,20121210,120,20121209103035,1239,0
T,.CITIBANK,1000,101,20121210,120,20121209103036,1240,0
P,ICICIBANK,1100,100,20121210,120,20121209103030,1241,1234
P,ICICIBANK,1100,100,20121210,120,20121209103035,1242,1239
”还是类似的东西,我都想在其中添加5个带有伪数据的行。
Dummy Record
如果上述查询的输出是这样的。
SELECT FirstName, (SELECT COUNT(*) FROM Student) Total
FROM Student
我希望输出像这样
FirstName Total
Isaac Frempong 2
Erick Ortiz 2
我希望这是可以实现的,我无法在这里弄清楚如何应用CASE或IF语句。也许有人可以帮忙。
答案 0 :(得分:4)
一种方法是使用VALUES()
语句构造行:
SELECT FirstName, COUNT(*) OVER () as Total
FROM Student
UNION ALL
SELECT 'Dummy', (SELECT COUNT(*) FROM Student)
FROM (VALUES (1), (2), (3), (4), (5)) v(n);
编辑:
如果您始终需要7行,请使用算术:
SELECT FirstName, COUNT(*) OVER () as Total
FROM Student
UNION ALL
SELECT 'Dummy', s.total
FROM (VALUES (1), (2), (3), (4), (5), (6), (7)) v(n) CROSS JOIN
(SELECT COUNT(*) as total FROM Student) s
WHERE v.n <= 7 - s.total;
s
答案 1 :(得分:2)
这是处理表变量的代码,我称为 @students
请用您自己的桌子替换
我已在此表中填充了一些数据,并测试了不同的案例(记录数小于7或大于7,并按您的意愿工作!)
1)首先创建一个名为@mytable的变量表,该表将由n条记录填充
如果学生表中的记录数等于或小于7,则n将为7
n将是学生表中的记录数(如果大于7)
2)然后使用CTE,row_number()函数在要添加记录号的学生表之间建立右外部联接。
declare @students as table(id int identity(1,1),firstname nvarchar(50))
insert into @students(firstname) values
('Ali ben Hassine'),
('Mohamed el Aabed'),
('Ali ben Hassine'),
('Mohamed el Aabed'),
('Mohamed el Aabed'),
('Tahar Harbi'),
('Hassine Ayari'),
('Ihsen Trabelsi'),
('Marwa Mostari'),
('Mourad Zmerli'),
('Hafedh Gabsi'),
('Miloud Filali');
declare @mytab as table(n int)
declare @n as int
select @n=count(distinct(firstname)) from @students
if @n<7 set @n=7
declare @i as int
set @i=1
while @i <@n+1
begin
insert into @mytab values(@i)
set @i=@i+1
end;
with cte as
(select row_number() over(partition by 1 order by firstname) r#,firstname,count(1) Total from @students group by firstname)
select isnull(cte.firstname,'Dummy') firstanme,isnull(cte.total,2) Total from cte
right outer join @mytab t2 on cte.r#=t2.n
[![enter image description here][1]][1]