countif 和 sumif 每行而不分组

countif and sumif each row without grouping

我正在尝试使用 SQL

计算 sumif 和 countif

这是开始的代码: SELECT
商品编号 , 供应商 , 成本 , 销售价格 从 countifExpirement

我正在尝试创建此输出:

前四列已经有数据,我正在尝试创建计算字段来计算重复项目、每个供应商的项目和供应商的成本。 在 excel 中轻松创建。有很多使用分组方法的示例,但我需要每一行都存在。

在标准 SQL 中,您将为此使用解析函数。然而,它们并非在每个 DBMS 中都可用。

select 
  itemid, supplier, cost, saleprice, 
  count(*) over (partition by itemid) as count_itemid, 
  count(*) over (partition by supplier) as count_supplier, 
  sum(cost) over (partition by supplier) as cost_suppler
from countifexpirement;

这里与sub-select相同,每个DBMS都可用:

select 
  itemid, supplier, cost, saleprice, 
  (
    select count(*) 
    from countifexpirement x 
    where x.itemid = countifexpirement.itemid
  ) as count_itemid, 
  (
    select count(*) 
    from countifexpirement x 
    where x.supplier = countifexpirement.supplier
  ) as count_supplier, 
  (
    select sum(cost)
    from countifexpirement x 
    where x.supplier = countifexpirement.supplier
  ) as cost_suppler
from countifexpirement;