在Sql中的group by之后添加一个空行

时间:2016-07-01 03:20:26

标签: sql winforms

我的数据库表中有一组值,我想在一组数据后添加一个空行。

这就是我所做的;

SELECT election AS Election, candidate AS Candidate, COUNT(candidate) AS [Result Count]
FROM result2
GROUP BY candidate, election

我的结果是;

Election   | candidate   |  Result Count
President  | Name One | 5
president | Second Name | 2
Secretary | Third Name | 4
Secretary | Fourth Name | 2

请在每组选举后加上一个空行。

谢谢。

1 个答案:

答案 0 :(得分:0)

我做了这个练习:

select tt.[Election],tt.[candidate],case tt.[Result Count] when 0 then null else tt.[Result Count] end as [Result Count]
from
(SELECT [Election],[candidate],seq as seq,[Result Count]
FROM
(
select t.[Election],t.[candidate], ROW_NUMBER()  OVER ( ORDER BY result2.id) as seq, '' AS [Result Count] from result2
cross apply ( select '' as [Election],'' as [candidate], null as [Result Count]) T
) T
UNION 
select result2.[Election],result2.[candidate], ROW_NUMBER()  OVER ( ORDER BY result2.id) as seq, COUNT(result2.candidate) AS [Result Count] 
from result2
group by result2.[Election],result2.[candidate],result2.ID

) tt
ORDER BY tt.seq,tt.Election desc

在空白行中[结果计数] = 0时返回null

使用Cross应用可以生成空白行