我试图使用SQL
找出sumif和countif以下是开始的代码:
SELECT
项目ID
,供应商
,成本
, 销售价格
来自countifExpirement
我试图创建此输出:
前四列已有数据,我试图创建计算字段来计算重复项目,每个供应商的项目和供应商的成本。 易于创建excel。有很多例子可以使用分组方法,但我需要每一行都存在。
答案 0 :(得分:2)
在标准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;
这与子选择相同,在每个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;