我有一個表tblAccount
。我想從表格中得到前四排。如果沒有記錄,我想獲得4個空白行。返回空行當沒有記錄sql server
select *
from tblAccount
o/p
----
AccountID AccountNo
1 #101
2 #102
NULL NULL
NULL NULL
以上應該是結果,如果兩個記錄在那裏。
我有一個表tblAccount
。我想從表格中得到前四排。如果沒有記錄,我想獲得4個空白行。返回空行當沒有記錄sql server
select *
from tblAccount
o/p
----
AccountID AccountNo
1 #101
2 #102
NULL NULL
NULL NULL
以上應該是結果,如果兩個記錄在那裏。
這應該工作。你可以用臨時表做同樣的事情,只需給它適當數量的字段和行。
with meganull(a,b) as (
select CAST(null as int),
CAST(null as varchar(max))
union all
select *
from meganull
)
select top 4 *
from (
select *
from tblAccount
union all
select *
from meganull) as sq
獲取轉換錯誤,因爲我在varchar中選擇的字段。 將varchar值「#101」轉換爲數據類型int時轉換失敗。 – user1204716
只需將每個字段轉換爲適當的數據類型即可。我已經更新了答案 – pyrospade
select TOP 4 AccountID,AccountNo
from
(
select 0 as srt,AccountID,AccountNo from tblAccount
union all
select 1 as srt,NULL as AccountID, NULL as AccountNo
union all
select 2 as srt,NULL as AccountID, NULL as AccountNo
union all
select 3 as srt,NULL as AccountID, NULL as AccountNo
union all
select 4 as srt,NULL as AccountID, NULL as AccountNo
) as t
order by srt,AccountID
試試這個...
Select * FROM (VALUES (1),(2),(3),(4)) AS value(tmpID) left join
(
select Row_Number() over (order by AccountID) as RowCtr, *
from tblAccount
) accountTable on tmpID = accountTable.RowCtr
我使用了類似的技術時,我就想辦法強制一定的行數在SSRS報告中顯示,其中空白行表示物理機架中的空點。
問:爲什麼你需要一些反常的東西? – paulsm4