我有一张表,其中包含有关产品的常规信息。另一个表有定价信息,两个表都是1:n相关的。因此,每种产品可能(至少)有1到n的价格。
现在我需要在视图中与产品一起显示其中一些价格。另外,为了形成一些行,我必须添加或增加其中一些价格。
在我的第一次尝试中,我使用子查询进行输出和操作。哪个有效,但性能是...... meh ...... 我考虑过使用变量来设置定价值一次,然后重复使用它们。如果我能够一次设置2个或更多变量会更好。但是如何?
我的基本查询如下:
SELECT *
FROM (
SELECT ProductNr,
Description,
Year, ROW_NUMBER() OVER
(PARTITION BY ProductNr ORDER BY Year DESC) RowRank
FROM Products
WHERE Year like '2014'
AND Manager = 1
)sub
WHERE RowRank = 1
子查询基本上设置如下:
(SELECT Price FROM PricingInfo
WHERE Manager = 1
AND year = Products.Year
AND no = 1
AND ArticleNr = Products.ProductNr)
我尝试使用
DECLARE @price float
-- other ones...
SELECT *
FROM (
SELECT ProductNr,
Description,
@price = (SELECT colXX FROM PricingInfo
WHERE Manager = 1
AND year = products.Year
AND row = 'Y'
AND ArticleNr = products.ProductNr),
@price*1.2 as PriceWithTax
Year, ROW_NUMBER() OVER
(PARTITION BY ProductNr ORDER BY Year DESC) RowRank
FROM Products products
WHERE Year like '2014'
AND Manager = 1
)sub
WHERE RowRank = 1
这可以使用这样的构造吗?
编辑[21:09] - @MatBailie请求了一些例子:
ProductNr|Description|Year
001| Teddy Bear|2012
002| Card game|2013
003| Book|2012
003| Book|2013
定价信息:
Category|No|Price|Notice| ID|Year
1 |1 |35,22|No Tax|001|2012
1 |2 |38,18|Tax |001|2012
1 |3 |19,91|Bought|001|2012
1 |1 |19,91|Bought|002|2013
答案 0 :(得分:0)
您可以尝试连接两个表,然后使用前一个表中连接表的值,而不是参数。
SELECT *
FROM (
SELECT P.ProductNr,
P.Description,
PInfo.Price,
PInfo.Price*1.2 as PriceWithTax
P.Year,
ROW_NUMBER() OVER (PARTITION BY P.ProductNr ORDER BY P.Year DESC) RowRank
FROM Products P
INNER JOIN (SELECT ArticleNr,
Year,
colXX [Price]
FROM PricingInfo
WHERE Manager = 1
AND row = 'Y') PInfo
ON P.ProductNr = PInfo.ArticleNr
AND P.Year = PInfo.Year
WHERE Year = '2014'
AND Manager = 1
) SUB
WHERE SUB.RowRank = 1
希望它有所帮助!
答案 1 :(得分:0)
SELECT *
FROM (
SELECT Products.ProductNr
,Products.[Description]
,P_Info.colXX AS Price
,P_Info.colXX * 1.2 AS PriceWithTax
,P.[Year]
,ROW_NUMBER() OVER (PARTITION BY P_Info.ProductNr ORDER BY P_Info.[Year] DESC) RowRank
FROM Products P INNER JOIN PricingInfo P_Info
ON P.ProductNr = P_Info.ArticleNr
WHERE P.[Year] LIKE '2014' AND P_Info.[Year] LIKE '2014'
AND P.Manager = 1 AND P_Info.Manager = 1
AND P_Info.[ROW] = 'Y'
)Q
WHERE RowRank = 1