我有两张桌子。他们有一列表明它是股票还是坏股票。现在我想在状态'Y'时设置值,这意味着总的坏库存值和&当来自销售的状态'N'总库存值&销售退货表。
这是我的代码:
SELECT
sr.IsBadStock as Status,
CASE
WHEN sr.IsBadStock = 'Y'
THEN (SUM(srd.Qty))
WHEN sr.IsBadStock = 'N'
THEN SUM(srd.Qty)
END
FROM
SaleReturn sr, SaleReturnDetail srd
WHERE
sr.SaleInvNo = srd.SaleInvNo
AND sr.Department = srd.Department
AND sr.Company = srd.Company
GROUP BY
sr.IsBadStock
这是我的输出:
Status | (no column name)
-------+------------------
N | 60
Y | 390
我希望这两个值设置标量变量,其中第一行的名称为@stockQty
&第二行@badStockQty
,以便我以后可以进行一些计算。有可能吗?
答案 0 :(得分:0)
使用MS SQL Server
DECLARE @Good int
,@bad int
SELECT @bad =
SUM(
CASE
WHEN r.IsBadStock = 'Y' THEN [Qty]
ELSE 0
END),
@Good =
SUM(
CASE
WHEN r.IsBadStock = 'N' THEN [Qty]
ELSE 0
END)
FROM Returned r
PRINT @good
PRINT @bad
答案 1 :(得分:0)
好像你想要一个基本的GROUP BY
:
SELECT
sr.IsBadStock as Status,
SUM(srd.Qty)
FROM
SaleReturn sr
JOIN SaleReturnDetail
ON sr.SaleInvNo = srd.SaleInvNo
AND sr.Department = srd.Department
AND sr.Company = srd.Company
GROUP BY
sr.IsBadStock
请注意切换到现代的,明确的JOIN
语法。