日期:2014-05-18 浏览次数:20451 次
select Product, sum((case when BS='B' then 1 else -1 end) *Quantity) from tb group by Product
------解决方案--------------------
不好意思,刚才的反了,参考以下
select Product, sum((case when BS='B' then -1 else 1 end) *Quantity) from tb group by Product
------解决方案--------------------
/*先分组*/
SELECT Product
WHERE Product=ProductRoot.Product) AS MyT FROM [tb] AS ProductRoot
GROUP BY Product
/*设A 为一个产品的进入货数总数
设B 为一个产品的进入货数总数
设C C=B-A
*/
/*A*/
SELECT SUM(Quantity) FROM [tb] WHERE Product=ProductRoot.Product AND BS='B'
/*B*/
SELECT SUM(Quantity) FROM [tb] WHERE Product=ProductRoot.Product AND BS='S'
结果:
/*代入A到分组中*/
SELECT Product, (SELECT SUM(Quantity) FROM [tb] WHERE Product=ProductRoot.Product AND BS='B')
FROM [tb] AS ProductRoot
GROUP BY Product
最终SQL语句
/*代入B到分组中结合A*/
SELECT Product, (SELECT SUM(Quantity) FROM [tb] WHERE Product=ProductRoot.Product AND BS='S')-(SELECT SUM(Quantity) FROM [tb] WHERE Product=ProductRoot.Product AND BS='B')
FROM [tb] AS ProductRoot
GROUP BY Product