在主查询之前发生的Ruby续集子查询

时间:2018-04-04 12:12:45

标签: sql ruby-on-rails ruby sequel

有人可以帮我解决这个问题吗?

我需要将以下sql代码翻译成续集:

SELECT DISTINCT sales_leads.employee_person_id,
    (SELECT full_name from persons 
        WHERE sales_leads.employee_person_id=persons.id),
    (SELECT COUNT (sales_leads.id) from sales_leads 
        WHERE sales_leads.employee_person_id=employees.person_id 
        AND sales_leads.status='open') AS open_leads_count,
    (SELECT COUNT (sales_leads.id) from sales_leads 
        WHERE sales_leads.employee_person_id=employees.person_id 
        AND sales_leads.status='lost' OR sales_leads.status='won') AS closed_leads_count
FROM sales_leads
JOIN employees ON sales_leads.employee_person_id=employees.person_id
ORDER BY sales_leads.employee_person_id;

这是我到目前为止所做的:

DB[:sales_leads]
  .inner_join(:persons, id: :employee_person_id)
  .select(:full_name)
  .select_append(
    DB[:sales_leads]
      .select(:id)
      .where(Sequel[:sales_leads][:employee_person_id]=>Sequel[:persons][:id])
      .count
  ).all

但是我收到了一个错误:

  

PG :: UndefinedTable:错误:缺少表的FROM子句条目   "人"第1行:...... eads" WHERE(" sales_leads"。" employee_person_id" =   "人" ....                                                                ^:SELECT count(*)AS" count" FROM" sales_leads"哪里   (" sales_leads"。" employee_person_id" ="人员"。" id")限制1   Sequel :: DatabaseError:PG :: UndefinedTable:错误:缺少FROM子句   表"人员"第1行:...... eads"哪里   (" sales_leads"。" employee_person_id" ="人员" ....                                                                ^来自/home/john/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/sequel-5.5.0/lib/sequel/adapters/postgres.rb:145:in   `async_exec'

1 个答案:

答案 0 :(得分:2)

您正在调用要传递给select_append调用的数据集上的Dataset#countDataset#count会运行查询。您可能需要.select{count(sales_leads[:id])}而不是.count