看板 Database 關於我們 聯絡資訊
※ 引述《ClubT (Debug能不能用殺蟲濟啊)》之銘言: : 我是用SQL SERVER 2000 : 現在我要篩選一個狀態的欄位 : select 編號,count(CASE 狀況 when 1 then 流水號 END), : count(CASE 狀況 when 2 then 流水號 END) from 表格名稱 group by 編號 : 結果就會出現每個編號 : 狀況=1 時的數量 和 狀況=2時的數量 : 但是如果我要同時篩選2個狀態 : 希望的結果是: : 編號,(狀態一=1 and 狀態二=1 的數量),(狀態一=1 and 狀態二=2 的數量), : (狀態一=2 and 狀態二=1 的數量),(狀態一=2 and 狀態二=2 的數量) : 像這樣 SQL語法 要怎麼下 : THANKS 這個 sql 有一點複雜 , 我想的到可以有兩個選擇 , 一個是先做出 group by no,狀態1,狀態2 查出各狀態的數量簡 view , 再從這 view 中撈出你想要的資料 , 出來再組合 . (只是這樣資料行就是縱向的了:p) ex. select no,state1,state2 ,count(id) as cnt from tb_data group by no ,stat1,state2 另一個比較符合原題 , 透過 subquery 來查. SELECT tb.no , ( select count(id) from tb_data where no=tb.no and state1=1 and stat2=1 ) , ( select count(id) from tb_data where no=tb.no and state1=1 and stat2=2 ), ( select count(id) from tb_data where no=tb.no and state1=2 and stat2=1 ) , ( select count(id) from tb_data where no=tb.no and state1=2 and stat2=2 ) from tb_data tb 雖然說第一眼看起來這樣效率好像很差 , 以前第一次看到這種寫法時是這樣想 , XD 我對 sql 的效率鑽研不深 , 我不太確定這樣會不會比較吃力 , 我自己曾經在幾萬筆資料的小 table 下類似的 query 是感覺還好的狀態 , 大的現在還沒機會碰...XD -- ps.以上是 m$ sql server 2005/2008 操作的經驗 , 2000實在是沒機會用到 , 我不確定有沒有差異...:p -- What do you want to have ? / What do you have? 從書本中,你可以發現我的各種興趣。 從CD中,你可以瞭解我所喜歡的偶像明星。 或許從文字你很難以瞭解一個人,但從物品可以。 My PPolis , My past. http://ppolis.tw/user/Tony -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 221.169.78.140 ※ 編輯: TonyQ 來自: 221.169.78.140 (05/11 16:53)