是否可以将“两个查询与聚合和组合”(结果集)组合起来?

时间:2010-09-22 15:59:32

标签: sql group-by aggregate sybase-ase

1

Select id,count(*) as totalX FROM my_table WHERE x_factor = 1 GROUP BY id

结果集

 id        totalX
 --------- --------------
         9             34
        10              6
        11             21
        12              3  

2

Select id,count(*) as totalY FROM my_table WHERE y_factor = 1 GROUP BY id

ResultSet 2:

 id        totalY
 --------- --------------
         9             334
        10              56
        11             251
        12              93 

有没有办法实现这一目标:

 id        totalX        totalY         
 --------- --------------  --------------  
         9             34              334 
        10              6               56 
        11             21              251 
        12              3               93 

我想在RHEL 5上使用Sybase 12.5的解决方案,我也想知道这是否可以在任何其他数据库系统中使用。

---感谢答案 -

Comparing EXECUTION TIME: (For a certain query) 
 Query 1:
Execution Time 61.
SQL Server cpu time: 6100 ms.  SQL Server elapsed time: 12133 ms.

Query 2:
Execution Time 53.
SQL Server cpu time: 5300 ms.  SQL Server elapsed time: 12090 ms.

Query X(1+2):
Execution Time 84.
SQL Server cpu time: 8400 ms.  SQL Server elapsed time: 21456 ms.

3 个答案:

答案 0 :(得分:4)

通过对列使用CASE / WHEN并根据true / false对1或0求和,可以在同一个查询中得到两个...另外,如果你想要一些总和,你可以做同样的事情另一列中的值...只需将其替换为真值而不是1。

select 
      id,
      sum( CASE WHEN x_factor = 1 THEN 1 ELSE 0 END ) as X_Count, 
      sum( CASE WHEN y_factor = 1 THEN 1 ELSE 0 END ) as Y_Count
  from
      yourTable
  group by
      id

答案 1 :(得分:1)

这应该有效:

SELECT id, 
       sum(case when x_factor = 1 then 1 else 0 end) as totalX,
       sum(case when y_factor = 1 then 1 else 0 end) as totalY
    FROM my_table 
    WHERE x_factor = 1 
        OR y_factor = 1
    GROUP BY id

答案 2 :(得分:1)

CASE ...... {0 | 1}对于人们来说是一个很好的技巧,但我认为问题可能比这更简单。你试过了吗?

SELECT id, COUNT(x_factor) AS count_x, COUNT(y_factor) AS count_y FROM my_table GROUP BY id