我有这两个表:
我的SQL声明:
SELECT TOP 5
t1.Product_ID,
t1.Name,
t1.Category,
(SELECT COUNT(*)
FROM Cart_Details
WHERE Cart_Details.Product_ID = t1.Product_ID) AmountSold,
(SELECT Quantity
FROM Cart_Details
WHERE t1.Product_ID = Cart_Details.Product_ID) AS Quantity,
(Quantity * AmountSold) AS FinalSold
FROM
[dbo].[Product] t1
我正在尝试将别名(AmountSold
和Quantity
)的值乘以并将结果设为FinalSold
,但我收到错误:
无效的列名称'AmountSold'。
和
无效的列名称'Quantity'。
我是否有其他方法可以将两个别名的值添加到新列中?
答案 0 :(得分:0)
使用计算字段的一种方法是将其包装在子查询中:
SELECT
*,
(Quantity*AmountSold)AS FinalSold
FROM (SELECT top 5
t1.Product_ID,
t1.Name,
t1.Category,
(select count(*)
from Cart_Details
where Cart_Details.Product_ID=t1.Product_ID ) AmountSold,
(select Quantity
from Cart_Details
where t1.Product_ID=Cart_Details.Product_ID) AS Quantity,
FROM [dbo].[Product] t1) AS InnerTable
答案 1 :(得分:0)
另一种方法是使用CTE:
;WITH CTEQuery AS
(SELECT
t1.Product_ID,
t1.Name,
t1.Category,
(select count(*)
from Cart_Details
where Cart_Details.Product_ID = t1.Product_ID) AmountSold,
(select Quantity
from Cart_Details
where t1.Product_ID=Cart_Details.Product_ID) AS Quantity
FROM [dbo].[Product] t1)
SELECT top 5 (Quantity*AmountSold) AS FinalSold, *
FROM CTEQuery