【问题标题】:Is combining (result sets) of "two queries with aggregate and group by" possible?是否可以组合“两个查询与聚合和分组依据”的(结果集)?
【发布时间】:2010-09-22 15:59:32
【问题描述】:

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

结果集 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.

【问题讨论】:

    标签: sql group-by aggregate sap-ase


    【解决方案1】:

    通过对列使用 CASE/WHEN 并根据真/假对 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
    

    【讨论】:

    • 啊..天才我为什么没想到:) 谢谢。如果有人关心,我已经用执行时间编辑了我的问题
    【解决方案2】:

    这应该可行:

    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
    

    【讨论】:

      【解决方案3】:

      CASE ... {0|1} 是一个让人们知道的好技巧,但我认为问题可能比这更简单。你试过了吗:

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

      【讨论】:

        猜你喜欢
        • 2014-02-23
        • 2022-01-06
        • 2020-08-12
        • 2012-07-14
        • 2018-06-24
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多