2010-09-22 239 views
2
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 
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 

我想爲Sybase 12.5的解決方案在RHEL 5,我也想知道這是否可能在任何其他數據庫系統。

---謝謝你的答案(S) - 基於真/假的,你可以在這兩個

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. 

回答

4

通過使用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 
+0

啊..天才爲什麼我沒有想到這一點:)謝謝。我編輯了我的問題與執行時間,如果有人關心 – Stewie 2010-09-22 16:35:36

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 
+0

謝謝..它的工作原理 – Stewie 2010-09-22 16:36:49

1

CASE ... {0 | 1}對於人們來說是一個很好的竅門,但我認爲這個問題可能比這更簡單。您是否嘗試過:

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