你不能有這樣的列的動態數量,但你可以串聯數據成字符串:
select
s.ItemID, s.Code, s.Name,
stuff(
(
select ', ' + CAST(sv.SearchValueID AS VARCHAR)
from ItemSearch as sv
where sv.ItemID = s.ItemID
for xml path(''), type
).value('.', 'nvarchar(128)')
, 1, 2, '') as SearchValues
from Item as s;
,或者你可以樞軸行與PIVOT command
或手動(我更喜歡後一種方法,它對我來說似乎更靈活,但pivot
可以g reatly減少在某些情況下)的代碼量:
with cte as (
select
*,
row_number() over(partition by sv.ItemID order by sv.SearchValueID) as row_num
from ItemSearch as sv
)
select
s.ItemID, s.Code, s.Name,
max(case when sv.row_num = 1 then sv.SearchValueID end) as SearchValueID1,
max(case when sv.row_num = 2 then sv.SearchValueID end) as SearchValueID2,
max(case when sv.row_num = 3 then sv.SearchValueID end) as SearchValueID3,
max(case when sv.row_num = 4 then sv.SearchValueID end) as SearchValueID4
from Item as s
inner join cte as sv on sv.ItemID = s.ItemID
group by s.ItemID, s.Code, s.Name
你也可以把前面的語句爲動態SQL這樣的:
declare @stmt nvarchar(max)
select
@stmt =
isnull(@stmt + ',','') +
'max(case when sv.row_num = ' + cast(rn as nvarchar(max)) +
' then sv.SearchValueID end) as SearchValueID' + cast(rn as nvarchar(max))
from (
select distinct row_number() over(partition by ItemID order by SearchValueID) as rn
from ItemSearch
) as a
select @stmt = '
with cte as (
select
*,
row_number() over(partition by sv.ItemID order by sv.SearchValueID) as row_num
from ItemSearch as sv
)
select
s.ItemID, s.Code, s.Name,' + @stmt + '
from Item as s
inner join cte as sv on sv.ItemID = s.ItemID
group by s.ItemID, s.Code, s.Name;'
exec dbo.sp_executesql @stmt = @stmt
sql fiddle demo
您的號碼的列取決於你的一對多表的垂直大小,我怕我沒有一個靜態曲輸出結果的ery,但你可以通過編程創建一個像@Roman的查詢來輸出這個結果 –
我會嘗試使用Roman的數據透視解決方案。將數據更改爲字符串不是最佳解決方案。 – kufer
也只是爲了澄清。列數是靜態的。在表StockItemCatSearchValueShort中,1個ItemID始終有4個SearchValueID。 – kufer