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.
通过为该列使用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