如何从查询中获取结果计数?

时间:2013-06-04 21:31:35

标签: sql count inner-join

我需要有关查询的帮助,或指向涵盖该问题的答案的链接:

我有两张表:STOCK_ITEMSSTOCK_LOC_INFO

STOCK_ITEMS有很多字段,但感兴趣的是STOCKCODESTOCK_CLASSIFICATION

STOCK_LOC_INFO包含针对每个STOCKCODE的每个库存位置(11个位置)的记录

STOCK_ITEMS

 item1,class 1
 item2,class 2
 item3,class 1

STOCK_LOC_INFO

item1,location1,qty1
item1,location2,qty2
item1,location3,qty3

等,为每个股票代码重复11行。

现在... 我想在11个地点中的5个找到某个类的库存数量(数量大于0)。我试过这个:

select COUNT(SOH.STOCKCODE)
from dbo.STOCK_ITEMS SOH
Inner join STOCK_LOC_INFO SLI
on SOH.STOCKCODE = SLI.STOCKCODE
where SLI.QTY > 0 and SLI.LOCATION in(1,2,3,9,11)

并得到了9790的结果 - 这太高了(预计大约900),因为它计算每次所需的部件号出现在Stock Loc表中超过0 ...但我只想要是或否每个股票代码,而不是每个数量。

我怀疑它需要COUNTIF或类似物。我迷路了!

任何帮助都非常感激。

4 个答案:

答案 0 :(得分:1)

您是否只想要符合您标准的不同股票代码? 如果是这样的话:

SELECT COUNT(DISTINCT SOH.STOCKCODE)
FROM STOCK_ITEMS SOH
INNER JOIN STOCK_LOC_INFO SLI
ON SOH.STOCKCODE = SLI.STOCKCODE
WHERE SLI.QTY > 0 AND SLI.LOCATION IN(1,2,3,9,11)

您还可以在加入前限制SLI表:

SELECT COUNT(SOH.STOCKCODE)
FROM STOCK_ITEMS SOH
INNER JOIN (SELECT DISTINCT STOCKCODE 
            FROM STOCK_LOC_INFO
            WHERE QTY > 0 AND LOCATION IN(1,2,3,9,11)
            )SLI
ON SOH.STOCKCODE = SLI.STOCKCODE

答案 1 :(得分:1)

如果我理解正确,这就是你想要的:

SELECT COUNT(*)
FROM (  SELECT SOH.STOCKCODE, COUNT(*) AS N
        FROM dbo.STOCK_ITEMS SOH
        INNER JOIN STOCK_LOC_INFO SLI
            ON SOH.STOCKCODE = SLI.STOCKCODE
        WHERE SLI.QTY > 0 AND SLI.LOCATION in(1,2,3,9,11)
        GROUP BY SOH.STOCKCODE
        HAVING COUNT(*) = 5) A

答案 2 :(得分:1)

尝试:

select count(1)
from dbo.STOCK_ITEMS SOH
inner join (select distinct STOCKCODE, LOCATION
             from STOCK_LOC_INFO
             where QTY > 0 and LOCATION in(1,2,3,9,11)) SLI
on SOH.STOCKCODE = SLI.STOCKCODE

它计算每个选定位置的QTY> 0的唯一STOCKCODE的总数。

答案 3 :(得分:1)

使用Oracle你可以这样做:

select COUNT(SOH.STOCKCODE)
  from dbo.STOCK_ITEMS SOH
 WHERE SOH.STOCKCODE IN (
              SELECT SLI.STOCKCODE
                FROM STOCK_LOC_INFO SLI
               where SLI.QTY > 0 
                 and SLI.LOCATION in(1,2,3,9,11)
                       )