假設我有值的數組:如何針對一系列值對運行查詢並將結果存儲在臨時表中?
(A1,A1,A2,A2,A3,A3,A4,A4 .....,一個,一個)
我應該怎樣和自動化對運行(A1,A1 ...,AN,一個)的下面TSQL查詢對
SELECT COUNT (1)
FROM food
WHERE calories = Ai AND ingredient = ai --i = {1..n}
這樣每個計數由(艾,AI)得到{I = 1..N}將存儲在臨時表中?
感謝
假設我有值的數組:如何針對一系列值對運行查詢並將結果存儲在臨時表中?
(A1,A1,A2,A2,A3,A3,A4,A4 .....,一個,一個)
我應該怎樣和自動化對運行(A1,A1 ...,AN,一個)的下面TSQL查詢對
SELECT COUNT (1)
FROM food
WHERE calories = Ai AND ingredient = ai --i = {1..n}
這樣每個計數由(艾,AI)得到{I = 1..N}將存儲在臨時表中?
感謝
插入您的數組中的值到一個臨時表(我將使用同一個用於後來的結果):
create table #pairs (
calories varchar(50),
ingredient varchar(50),
count int
)
然後,我們可以得到我們的結果一步到位:
UPDATE p
SET count = x.count
FROM #pairs p inner join
( SELECT f.calories, f.ingredient, COUNT(*) as count
FROM food f inner join
#pairs p ON f.calories = p.calories and f.ingredient = p.ingredient
GROUP BY f.calories, f.ingredient
) x ON p.calories = x.calories and p.ingredient = x.ingredient
select * from #pairs
你可以用SQL DYNAMIX,像這樣做:
declare @count int, @limit int
select @count = 0, @limit = 5 -- limit is n
declare @sqlcmd varchar(300)
-- table
create table #result (
combination varchar(10),
total int
)
while @count < @limit
begin
select @sqlcmd = 'insert into #results select distinct "(" + ingredient + "," + calories + ")", count(*) from food where calories = A' + convert(varchar, @count) + ' and ingredient = a' + convert(varchar, @count)
exec(@sqlcmd)
select @count = @count + 1
end
我假設有A1,A2,A3的數組..一種成分和a1,a2,a3 ..卡路里,但如果它不是我可以改變它,只要在這裏說點什麼:) –
在sql數據庫的臨時表中? – Brian
你在哪個表格中有'A1,a1,A2,a2,A3,a3,A4,a4 .....,An,an'? – sll