Sql 是否可以将“聚合和分组方式的两个查询”(结果集)组合在一起?

Sql 是否可以将“聚合和分组方式的两个查询”(结果集)组合在一起?,sql,group-by,aggregate,sap-ase,Sql,Group By,Aggregate,Sap Ase,一, 结果集: 二, 结果集2: 我有没有办法做到这一点: 我想要RHEL 5上Sybase 12.5的解决方案,我也想知道这在任何其他数据库系统中是否可行 --谢谢你的回答- id totalX totalY --------- -------------- -------------- 9 34 334 10 6

一,

结果集:

二,

结果集2:

我有没有办法做到这一点:

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

--谢谢你的回答-

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

通过对列使用CASE/WHEN,并根据true/false对1或0求和,可以在同一查询中同时获得这两个值。。。此外,如果希望在另一列中求某个值的和,也可以执行相同的操作。。。只需将其替换为真值,而不是1

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.
这应该起作用:

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

这个案子。。。{0|1}对于人们来说是一个很好的技巧,但我认为问题可能比这简单。您是否尝试过:

选择id, COUNTx_因子作为count_x, 作为计数的县系数 从我的桌子上
按id分组

Ah。。天才我为什么没想到:谢谢你。如果有人在乎的话,我已经用执行时间编辑了我的问题
 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 
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.
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
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