2012-02-08 12 views
0

私は各項目の行がステータスを持つ簡単なテーブル構造を持っています。私が探しているのは、各ステータスを照会し、そのステートを使用するアイテムの数を数えることです。すべてのステータスが使用されるわけではない可能性があるので、NULLとゼロカウントを考慮する必要があります。次のようにフィルタright join data where句

私のテーブル構造は次のとおりです。

Table: Items 
Id, State_id, Text, Status 

Table: States 
State_id, Name 

は、これは私が持っているものです。

SELECT statealias1_.State_id as y0_, 
     count(this_.Id)  as y1_ 
FROM  Items this_ 
     right join States statealias1_ 
      on this_.State_id = statealias1_.State_id 
WHERE (not (statealias1_.State_id in (5, 6, 7, 8)) 
      or statealias1_.State_id is null) 
     and (this_.Status = 'InProgress' 
      or this_.Status is null) 
GROUP BY statealias1_.State_id; 

すべての状態(8つの状態があるが含まれており、私は2番目を除いていたときに、このクエリは動作しますハーフ)。なぜ私はこれが返されないのか分かりませんすべて州はNULLに関係なくcountsで状態を保持しています。

答えて

2
select i.State_id as y0_, count(i.Id) as y1_ 
from Items i 
left join States s on i.State_id = s.State_Id and i.Status = 'InProgress' 
group by i.State_id 
+0

私の謝罪を。 'State_id'と' Status'は2つの別々の列です。私はそれに応じて私の質問を変更しました。 – Nosila

+0

'Status'が 'InProgress'になるようにフィルタリングを開始すると、使用されていない状態は返されません。 – Nosila

+0

残念ながら、私は今、どこにnullsを含めることができないのですか?( – Nosila

1

私は...それを逆にあなたの「ステータス」のエントリで始まり、LEFTあなたが接近しているが、

select 
     S.State_ID, 
     COALESCE(PreAgg.ICount, 0) as StateCount 
    from 
     States S 
     LEFT JOIN (select I.State_ID, count(*) as ICount 
         from Items I 
         where NOT I.State_ID IN(5, 6, 7, 8) 
          AND I.Status = 'InProgress' 
         group by I.State_ID) PreAgg 
      on S.State_ID = PreAgg.State_ID 
1

を含めるようにしたい何の事前集計結果セットに登録しようあなたは私がいつもそれが終わるのを見る方法からそれを逆に持っています。

SELECT s.State_id, COUNT(i.Id) 
FROM States AS s 
LEFT OUTER JOIN Items AS i ON i.State_id = s.State_id 
WHERE ... 
GROUP BY s.State_id 
1

あなたのSQLは正しいと思いますが、あなたの条件には論理エラーがあります。

あなたはしている:

WHERE (
      NOT (statealias1_.State_id in (5, 6, 7, 8)) 
      OR statealias1_.State_id is null 
) 
AND  (this_.Status = 'InProgress' or this_.Status is null) 

はもしかして:

WHERE NOT (
       statealias1_.State_id in (5, 6, 7, 8) 
       OR statealias1_.State_id is null 
     ) 
     AND (this_.Status = 'InProgress' or this_.Status is null)