【问题标题】:Calculate division between outputs of 2 different tables计算 2 个不同表的输出之间的除法
【发布时间】:2020-05-22 15:08:51
【问题描述】:

我正在尝试计算废品率。这样我的输出就会给出类似的东西。

Scrap Product Total Count 
-------------------
Product Total Count

我有两张桌子:

Product
--------
Barcode 1
Barcode 2 
Barcode 3
Barcode 4 

废品

Barcode 2
Barcode 4

我一直在尝试使用枢轴运算符进行不同的查询,并在下面进行查询。 实现这一目标的最佳方法是什么?

select (
select count(barcode)
FROM ScrapProduct)
 / 
(
select count(barcode)
FROM Product) as total_count

【问题讨论】:

    标签: sql sql-server tsql pivot


    【解决方案1】:

    您的代码基本上没问题。但是你会遇到整数除法的问题。因此,您的数字中需要小数。我发现这是最简单的方法:

    select ( (select count(barcode) from ScrapProduct) * 1.0 / 
             (select count(barcode) from Product)
           ) as scrap_rate
    

    如果您想要三列,则将子查询移至from 子句:

    select num_scrap, num_product, (num_scrap  * 1.0 / num_product) as scrap_rate 
    from (select count(barcode) as num_scrap from ScrapProduct) sp cross join
          (select count(barcode) as num_product from Product) p
    

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      相关资源
      最近更新 更多