[英]counting using join information
I have two tables. 我有两张桌子。
One table records orderstock which has FK_stock and FK_orderNo 一个表记录了具有FK_stock和FK_orderNo的订单集
I want to count the number of orders each item of stock has. 我想计算每个股票的订单数量。 The following code works correctly to do this: 以下代码可以正常执行此操作:
(1)
SELECT orderstock.FK_orderNo, Count(orderstock.FK_stock) AS CountOfFK_stock
FROM stock INNER JOIN orderstock ON stock.StockID = orderstock.FK_stock
GROUP BY orderdemo.FK_orderNo
However, I wish to add to this such that only stock items which are non perishable (stock.perishable=0) are listed. 但是,我想补充一点,只列出非易腐物品(stock.perishable = 0)的库存物品。 So something like 所以像
SELECT orderstock.FK_orderNo, Count(orderstock.FK_stock) AS CountOfFK_stock
FROM stock INNER JOIN orderstock ON stock.stockID = orderstock.FK_stock
WHERE stock.perishable=0
GROUP BY orderstock.FK_orderNo
How do I access information relating to the FK_stock to make this work? 如何访问与FK_stock相关的信息以使其工作? When I attempt to combine information from the stock table to this end, each item of stock is counted separately. 当我尝试将库存表中的信息组合到此时,每个库存项目将单独计算。
Results from (1) 结果(1)
FK_OrderNo CountOfFK_Stock
9 10
104 8
105 3
106 10
107 8
108 10
109 11
110 9
Desired results (something like): 期望的结果(类似):
FK_OrderNo CountOfFK_Stock
9 7
104 8
105 3
106 4
107 7
108 2
109 11
110 6
I guess you are looking for conditional count
我想你正在寻找conditional count
Move the where
clause filter to Count Aggregate
and make the count aggregate to count the record only when stock.perishable = 0
. 将where
子句过滤器移动到Count Aggregate
并使count聚合仅在stock.perishable = 0
时计算记录。
SELECT orderdemo.fk_orderno,
Count(CASE
WHEN stock.perishable = 0 THEN 1
END) AS nonperishable_count
FROM stock
INNER JOIN orderdemo
ON stock.studentid = orderdemo.fk_stock
GROUP BY orderdemo.fk_orderno
Count
Aggregate can be replaced by SUM
aggregate as well. Count
Aggregate也可以由SUM
聚合替换。 Something like this 像这样的东西
Sum(CASE
WHEN stock.perishable = 0 THEN 1
ELSE 0
END) AS nonperishable_count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.