|
SELECT A_x.ModelInfoNO, z. [ModelNO], z. [TradeName], z. [EnscapMode], z. [Quality], z. [BatchNO],
A_y.ShopWarehouseNO,
ISNULL (InStockInfo.InStock_Count, 0) AS InStock_Count,
ISNULL (OutStockInfo.OutStock_Count, 0) AS OutStock_Count,
FROM
(
SELECT DISTINCT ModelInfoNO FROM [InStockOrder Details]
union
SELECT DISTINCT ModelInfoNO FROM [OutStockOrder Details]
)
A_x,
(
SELECT DISTINCT InShopWarehouseNO AS ShopWarehouseNO FROM [InStockOrders]
union
SELECT DISTINCT OutShopWarehouseNO FROM [OutStockOrders]
) A_y
LEFT JOIN
(
SELECT A.ModelInfoNO, B.InShopWarehouseNO, SUM (A.Quantity) as InStock_Count
FROM [InStockOrder Details] A, [InStockOrders] B
WHERE A. [InStockOrderNO] = B. [NO]
GROUP BY A. ModelInfoNO, B. InShopWarehouseNO
) InStockInfo
ON InStockInfo.ModelInfoNO = A_x.ModelInfoNO AND InStockInfo.InShopWarehouseNO = A_y.ShopWarehouseNO
LEFT JOIN
(
SELECT A.ModelInfoNO, B.OutShopWarehouseNO, SUM (A.Quantity) as OutStock_Count
FROM [OutStockOrder Details] A, [OutStockOrders] B
WHERE A. [OutStockOrderNO] = B. [NO]
GROUP BY A. ModelInfoNO, B.OutShopWarehouseNO
) OutStockInfo
ON OutStockInfo.ModelInfoNO = A_x.ModelInfoNO AND OutStockInfo.OutShopWarehouseNO = A_y.ShopWarehouseNO
LEFT JOIN
ShopWarehouseInfo y1 ON y1. [ID] = A_y.ShopWarehouseNO
LEFT JOIN
ModelsInfo z ON A_x.ModelInfoNO = z. [NO]
ORDER BY InStock_Count DESC,
OutStock_Count DESC
The main idea is: According to ModelInfoNO and ShopWarehouseNO, group statistics on the InStock and OutStock tables, (ModelInfoNO and ShopWarehouseNO are passed into the subquery from the outside, they have nothing to do with each other).
Don't know why, if I put A_x in the main query FROM ",
(
SELECT DISTINCT InShopWarehouseNO AS ShopWarehouseNO FROM [InStockOrders]
union
SELECT DISTINCT OutShopWarehouseNO FROM [OutStockOrders]
) A_y
"This is removed. The A_y.ShopWarehouseNO in it is replaced by a constant (such as 2 or 3), and it will work well. However, the result of this query is ShopWarehouseNO for the specified data.
If I don't remove A_y, the query analyzer reports the following error.
Server: Msg 107, Level 16, State 2, Line 3
The column prefix 'A_x' does not match with a table name or alias name used in the query.
why? |
|