【问题标题】:Sum union calculated value in SQL在 SQL 中求和联合计算值
【发布时间】:2017-06-16 17:18:23
【问题描述】:

我想总结两个 SELECT 语句。两个查询都可以正常工作,但我无法对总计的输出求和。我尝试关注此question,但无法通过将查询包装在select id, sum(amount) from ( ) 中来求和

SELECT "patient_profiles"."id", count(distinct recommendations.id) AS total
FROM "patient_profiles" 
  LEFT OUTER JOIN 
  "recommendations" ON "recommendations"."patient_profile_id" = "patient_profiles"."id" 
GROUP BY "patient_profiles"."id"

UNION

SELECT "patient_profiles"."id", count(distinct patient_profile_potential_doctors.id) AS total
FROM "patient_profiles" 
  LEFT OUTER JOIN "patient_profile_potential_doctors" ON "patient_profile_potential_doctors"."patient_profile_id" = "patient_profiles"."id"       
GROUP BY "patient_profiles"."id"

【问题讨论】:

  • 您说“无法通过将查询包装在 select id, sum(amount) from ( ) 中来求和”,您是否收到错误消息?你把金额改成总数吧?

标签: sql postgresql join left-join


【解决方案1】:
    Select ID, sum(Total) from  
      (
        SELECT "patient_profiles"."id" [ID], count(distinct recommendations.id) AS total
        FROM "patient_profiles" 
          LEFT OUTER JOIN 
          "recommendations" ON "recommendations"."patient_profile_id" = "patient_profiles"."id" 
        GROUP BY "patient_profiles"."id"

        UNION

        SELECT "patient_profiles"."id" [ID], count(distinct patient_profile_potential_doctors.id) AS total
        FROM "patient_profiles" 
          LEFT OUTER JOIN "patient_profile_potential_doctors" ON "patient_profile_potential_doctors"."patient_profile_id" = "patient_profiles"."id"       
        GROUP BY "patient_profiles"."id"
) x
    group by ID

【讨论】:

  • 我使用 postgresql ERROR: cannot subscript type integer because it is not an array 得到以下错误
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
相关资源
最近更新 更多