根据不同的条件统计不同表的列,并按公共列连接分组(SQL)

Count columns of different tables based on different criteria and group by a common column join (SQL)

我有两个表,我想根据特定条件在其中查找特定列的计数。 (在 Zoho Analytics 上实施)

基本上:

  1. 表 1:计算名为 calltype 的列的字段值为 demo 的行数
  2. 表 2:计算名为 customertype 的列的字段值为 0 的行数
  3. 根据两者中存在的日期列以月份为单位对结果进行分组

我试过使用 sumcase,但它没有 return 正确的值 -

SELECT
         absmonth(A."Call Date") as Period,
         SUM(CASE WHEN A."Call Type"  = 'Demo' THEN 1 ELSE 0 END) AS TotalDemos,
         absmonth(B."modified") as Period1,
         SUM(CASE WHEN B."customertype"  = 0 THEN 1 ELSE 0 END) AS TotalTrials
FROM  "customer_calls" AS  A, "users" AS  B 
WHERE    B."modified"  = A."Call Date"
GROUP BY Period, Period1

但是,我有代码可以计算各个表中的每个计数值,这些值可以完美地给出结果 -

表 1

 SELECT
             absmonth("Call Date") as Period,
             Count("Call Type") as Total
    FROM  "customer_calls" 
    WHERE    "Call Type"  = 'Demo'
    GROUP BY  Period 

Table2(我本可以在这里避免 sumcase 但想检查它是否给出了正确的结果并且确实如此)

SELECT
         absmonth(B."modified") as Period1,
         SUM(CASE WHEN B."customertype"  = 0 THEN 1 ELSE 0 END) AS TrialCount
FROM  "users" AS  B 
GROUP BY  Period1 

基本上,作为最终结果,我想按月查找 TotalDemos 与 TotalTrials 的比率。有人可以指出我在第一个代码中哪里出错了吗?

Basically as an end result I want to find the ratio of TotalDemos to TotalTrials by Month.

尝试使用 union all 然后 sggregate:

select period, sum(num_demos), sum(num_trials),
       sum(num_demos) * 1.0 / sum(num_trials)
from ((select absmonth("Call Date") as Period,
              Count(*) as num_demos, 0 as num_trials
       from "customer_calls" 
       where "Call Type"  = 'Demo'
       group by Period 
      ) union all
      (select absmonth(u."modified") as Period,
              0, count(*) as num_trials
       from  "users" u
       where u."customertype"  = 0
       group by Period
      )
     ) dt
group by period;

我已经使用了您的查询结构。例如,我从未听说过一个名为 absmonth() 的函数。但这应该让您知道该怎么做。

我要提醒您的是,您不只是想要这样的查询的月份;你还应该考虑年份。