create table #sample ( product varchar(100), Price float ) insert into #sample values ('Pen',10) insert into #sample values ('DVD',29) insert into #sample values ('Pendrive',45) insert into #sample values ('Mouse',12.5) insert into #sample values ('TV',49) select * from #sample
考虑这种情况…
我有1000美元,我想购买上面列出的东西。
我想花全部钱
因此,我需要一个查询,该查询将给出所有产品中多少单位的价格为1000 $
有什么帮助吗?
这是硬编码的,几乎没有灵活性。我的系统花了2分钟才能运行。但是可能会有所帮助,如果没有,抱歉。fnGenerate_Numbers是一个表函数,它返回参数范围内的整数。 做到这一点的方法。
DECLARE @Max INT, @Pens money, @Dvds money, @Pendrives money, @Mouses money, @Tvs money SELECT @Max = 1000, @Pens = 10, @Dvds = 29, @Pendrives = 45, @Mouses = 12.5, @Tvs = 49 ;WITH Results AS ( SELECT p.n pens, d.n dvds, pd.n pendrives, m.n mouses, t.n tvs, tot.cost FROM fnGenerate_Numbers(0, @Max/@Pens) p -- Pens CROSS JOIN fnGenerate_Numbers(0, @Max/@Dvds) d -- DVDs CROSS JOIN fnGenerate_Numbers(0, @Max/@Pendrives) pd -- Pendrives CROSS JOIN fnGenerate_Numbers(0, @Max/@Mouses) m -- Mouses CROSS JOIN fnGenerate_Numbers(0, @Max/@Tvs) t -- Tvs CROSS APPLY (SELECT p.n * @Pens + d.n * @Dvds + pd.n * + @Pendrives + m.n * @Mouses + t.n * @Tvs cost) tot WHERE tot.cost < @Max ), MaxResults AS ( SELECT MAX(pens) pens, dvds, pendrives, mouses, tvs FROM Results GROUP BY dvds, pendrives, mouses, tvs ) SELECT mr.*, r.cost FROM MaxResults mr INNER JOIN Results r ON mr.pens = r.pens AND mr.dvds = r.dvds AND mr.pendrives = r.pendrives AND mr.mouses = r.mouses AND mr.tvs = r.tvs ORDER BY cost