【问题标题】:Join query confusion - I don't know how to join the 3 queries加入查询混乱 - 我不知道如何加入 3 个查询
【发布时间】:2018-08-04 07:22:19
【问题描述】:

第一个查询:

select 
    pid, month(dates) as month, sum(quan) as quan 
from 
    purchase 
where 
    month(dates) between 1 and 12 
    and pid = 4 
group by 
    pid, month(dates) 

第二次查询:

select 
    pid, month(dates) as months, sum(quan) as TotalAmount 
from 
    inward 
where 
    month(dates) between 1 and 12 
    and pid = 4 
group by 
    pid, month(dates) 

第三次查询:

select 
    pid, month(dates) as months, sum(quan) as TotalAmount 
from 
    issue 
where 
    month(dates) between 1 and 12 
    and pid = 4 
group by 
    pid, month(dates)

我不知道如何加入这些查询以输出 pid 是外键

【问题讨论】:

  • 您使用的是哪个 DBMS?甲骨文? MySQL? SQL 服务器? ...
  • SQL 服务器正在使用中

标签: sql sql-server-2008 join


【解决方案1】:

加入三个查询,就好像它们是表一样。您需要在它们周围加上括号,即from (...) join (...):

select
  pid, 
  month,
  coalesce(sum_purchase.total, 0) as total_purchase,
  coalesce(sum_inward.total, 0) as total_inward,
  coalesce(sum_issue.total, 0) as total_issue
from
(
  select pid, month(dates) as month, sum(quan) as total
  from purchase 
  where pid=4 
  group by pid, month(dates)
) sum_purchase
full outer join
(
  select pid, month(dates) as month, sum(quan) as total
  from inward 
  where pid=4 
  group by pid, month(dates)
) sum_inward using (pid, month)
full outer join
(
  select pid, month(dates) as month, sum(quan) as total
  from issue 
  where pid=4 
  group by pid, month(dates)
) sum_issue using (pid, month)
order by pid, month;

这是标准 SQL,应该可以在许多 DBMS 中使用。然而,有些不支持完全外部连接,有些不支持使用子句。所以你可能需要稍微调整一下。

【讨论】:

    【解决方案2】:

    尝试使用 join 语句

    SELECT
    pid,month(dates) AS month,sum(quan) AS quan 
    FROM purchase 
        INNER Join
    pid,month(dates) AS months , sum(quan) AS TotalAmount
    FROM inward
        INNER JOIN
    pid,month(dates) AS months , sum(quan) AS TotalAmount
    FROM issue
    WHERE month(dates) between 1 and 12 AND pid=4
    GROUP BY pid, month(dates)
    

    【讨论】:

    • 它显示这样的错误消息-','附近的语法不正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2015-04-11
    • 1970-01-01
    • 2012-07-24
    • 2020-11-24
    相关资源
    最近更新 更多