【问题标题】:How can I run a query against a series of value pairs and store the results in a temporary table?如何对一系列值对运行查询并将结果存储在临时表中?
【发布时间】:2012-01-19 10:29:01
【问题描述】:

假设我有一个值数组:

(A1,a1, A2,a2, A3,a3, A4,a4....., An,an)

我应该如何自动化并针对 (A1,a1..... ,An,an) 对运行以下 TSQL 查询

SELECT COUNT (1)
FROM food
WHERE calories = Ai AND ingredient = ai --i = {1..n}

那么(Ai,ai){i=1..n}得到的每一个计数都会存储在一个临时表中?

谢谢

【问题讨论】:

  • 在sql数据库的临时表中?
  • 你的A1,a1, A2,a2, A3,a3, A4,a4....., An,an是哪种形式的?

标签: sql tsql parameters parameter-passing


【解决方案1】:

将数组中的值插入临时表(稍后我将使用相同的结果):

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

【讨论】:

    【解决方案2】:

    您可以使用 dynamix SQL 来做到这一点,如下所示:

    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.. 一种卡路里,但如果不是我可以更改它,请在这里说一下 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多