我真的必须为此编写8个不同的SQL查询吗?

时间:2010-11-23 14:52:53

标签: sql oracle

我正在尝试编写一个查询,该查询将在多个列上执行COUNT,按其各自的列对它们进行分组。

以下是我现在的查询:

SELECT COUNT(*) as total,
COUNT(q3_pay) as q3_pay_total,
COUNT(q3_holidays) as q3_holidays_total,
COUNT(q3_vacation) as q3_vacation_total,
COUNT(q3_sick) as q3_sick_total,
COUNT(q3_insurance) as q3_insurance_total,
COUNT(q3_retirement) as q3_retirement_total,
COUNT(q3_fsa) as q3_fsa_total
FROM exit_responses

我需要找到两件事:

  1. 每列COUNT(列)的回复总数。
  2. 每列COUNT(列[x])< - 示例
  3. 的响应X总数

    有没有办法让我在不为每列创建新的SQL查询的情况下执行此操作?

    我目前还有其他查询,例如:

    SELECT COUNT(*) as total, q2 FROM exit_responses
    GROUP BY q2
    

    谢谢大家:)。

4 个答案:

答案 0 :(得分:1)

您需要提供表格的定义和一些示例数据行。

话虽如此,以下内容应该有效。

SELECT COUNT(*) as total,
sum(nvl(q3_pay,0)) as q3_pay_total,
sum(nvl(q3_holidays,0)) as q3_holidays_total,
...
FROM exit_responses

不确定这是否是您要找的。

答案 1 :(得分:0)

这取决于您的数据,如果这些是您想要的,但您可以做两件事:

  1. GROUP BY所有不同的列,然后使用COUNT(DISTINCT col)获取该列中不同值的数量

  2. GROUP BY任何合适的列,然后SUM(IF(col = 'xy',1,0))计算值达到某个条件的频率

答案 2 :(得分:0)

Count()将为每列返回相同的数字。你需要做的是每个的SUM()。确保将每个值的值更改为1,具体取决于内容。 (您可以在总和中使用案例来执行此操作)

答案 3 :(得分:0)

正如其他人所说,请发布DDL或表格以及一些样本行和预期的输出。

嗯,我不认为这是你想做的事情?

select 'Q3'                   as quarter,
       count(*)               as total,
       count(q3_pay)          as q3_pay_total,
       count(q3_holidays)     as q3_holidays_total,
       count(q3_vacation)     as q3_vacation_total,
       count(q3_sick)         as q3_sick_total,
       count(q3_insurance)    as q3_insurance_total,
       count(q3_retirement)   as q3_retirement_total,
       count(q3_fsa)          as q3_fsa_total
  from exit_responses
union all
select 'Q2'                   as quarter,
       count(*)               as total,
       count(q2_pay)          as q2_pay_total,
       count(q2_holidays)     as q2_holidays_total,
       count(q2_vacation)     as q2_vacation_total,
       count(q2_sick)         as q2_sick_total,
       count(q2_insurance)    as q2_insurance_total,
       count(q2_retirement)   as q2_retirement_total,
       count(q2_fsa)          as q2_fsa_total
  from exit_responses