【问题标题】:select count of rows minus sum of another field选择行数减去另一个字段的总和
【发布时间】:2014-06-02 20:03:52
【问题描述】:

我有三个名为agencyworkspurchases 的表。在purchasesworks 中有一个来自agency 的外键。每个机构都为我们工作,这些作品保存在works 表中,每完成一件作品都会给一分。例如,一个机构为我们做了 200 项工作,所以它有 200 分。
每个代理商都可以通过他们的积分购买我们的产品。在purchases 表中有一个名为price 的字段,如果代理商购买产品,它将插入到purchases 表中。 我需要一个 SQL 查询,它给我每个代理商的作品数量减去其购买的总和!

喜欢:

select count(works.WID)-SUM(purchases.price) where agency.aid='1'

例如:
像这样的机构:

 AID='1' name='FirstAgency'  

做一些工作,例如:

WID='1' AID='1' Description='Clean the floor'  
WID='2' AID='1' Description='Clean the window' 
WID='3' AID='1' Description='Clean the floor'  
WID='4' AID='1' Description='Clean the window' 
WID='5' AID='1' Description='Clean the floor'  
WID='6' AID='1' Description='Clean the window' 

所以 FirstAgency 有 6 分,因为 Works 表中有 6 行 AID='1'
而FirstAgency买了一个产品价格为2的产品。像Purchases表中这样:

PID='1' AID='1' Price='2'  

所以这个机构现在有 6-2=4 分。我需要一个查询来执行此操作,计算剩余的代理点数。

【问题讨论】:

  • 写这样的查询有什么问题?
  • 请编辑您的问题并提供示例数据和所需结果。这通常是传达所需内容的最有效方式。
  • 您尝试了哪些查询,为什么对结果不满意或出现什么错误?
  • 获得一些想法,从机构内部加入工作中选择 COUNT(*) 在没有存在的机构.col=work=col 上(从购买中选择 SUM(purchases.price),其中机构.col=purchases= col group by agencyid ) group by agencyid

标签: sql sql-server


【解决方案1】:

所以问题是你有 n 个作品和 m 个购买并且你不想加入表格,因为你会突然遇到 n * m 条记录。

你可以这样做:

select
  (select count(*) from works w where w.id_agency = a.id_agency) as count_works,
  (select sum(p.price) from purchases p where p.id_agency = a.id_agency) as sum_purchases
from agency a
where a.id_agency = 1;

这也可以通过连接实现,但您需要一些数学运算来混淆语句。为了完整起见,我将仅显示它。

select
  count(distinct w.id_work) as count_works,
  coalesce(sum(p.price),0) / greatest(count(distinct w.id_work),1) as sum_purchases
from agency a
left join works w on w.id_agency = a.id_agency
left join purchases p on p.id_agency = a.id_agency
where a.id_agency = 1;

【讨论】:

  • 只是好奇,但是greatest 是什么时候添加到 SQL 语言中的?
  • @NickyvV:我不认为它是标准的,但许多 dbms 都支持它(Oracle、Postgres、MySQL 等)。
  • greatest 不受 sql server 支持
  • @Thomas Haratyk:啊,好吧,我错过了 SQL Server 标记。然而,没问题,因为它在这里所做的只是用 1 替换 0。这可以用 case 结构替换:CASE WHEN count(distinct w.id_work) = 0 THEN 1 ELSE count(distinct w.id_work) END
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2016-12-25
相关资源
最近更新 更多