对SQL count()值进行计算

时间:2012-09-22 16:22:06

标签: mysql sql

我希望计算仓库中的项目并计算仓库中的可用空间,然后输出到具有Inshelf列的表并且是免费的,我想出了类似的东西。

SELECT COUNT(*) as Inshelf, free=10-Inshelf
  FROM stock.stockproduct 
 WHERE StockNum = 1
   AND checkOutData is NULL;

似乎它不起作用,是否有针对此类问题的任何简单解决方案?

2 个答案:

答案 0 :(得分:3)

这不起作用 - 聚合函数的结果(例如count())在考虑完所有记录之后才可用。你需要使用子查询,在子查询中进行计数,在外部查询中进行减法。在不知道您的数据库架构的情况下,这充其量是猜测,但是......

SELECT InShelf, free - InShelf
FROM (
    SELECT count(*) AS Inshelf, free
    FROM stockproduct
    WHERE StockNum = 1 AND checkOutData IS NULL
    GROUP BY somefield
) AS a

答案 1 :(得分:0)

工作!!

SELECT InShelf, 10 - InShelf
FROM (
    SELECT count(*) AS Inshelf, count(*) AS free
    FROM stock.stockproduct
    WHERE StockNum = 1 AND checkOutData IS NULL

) AS a;

感谢所有人,并因为愚蠢=。='

而骄傲