0

Oracle 10.2を使用していて、次のクエリがあります。

    select h.company, count(*)  
    from history h 
    where h.status = '2'  
    and h.substatus = '0'  
    and h.timestamp > '2012-01-01'  
    and h.timestamp < '2012-02-01'  
    group by h.company
    having (h.company = 'AAA')  
    or (h.company = 'BBB')  
    or (h.company = 'CCC')  
    order by h.company  

これは、AAA、BBB、またはCCCの企業の顧客が特定のポイント(ステータス= 2)に到達した回数をカウントします。
BBBの顧客がいない(ゼロ)と仮定すると、結果は2行のカウント(AAAとCCC)で返されます。

必要なもの:カウントがゼロの場合でも、クエリで3社すべての行が返されるようにしたいと思います。

クエリのレイアウトがおかしいのでごめんなさい。MSExcelでも動作するように作られています。

編集:申し訳ありません..カフェインが少なすぎます。クエリの後半の「顧客」を「会社」に変更しました。

明確化:「h.company」と「h.customer」を組み合わせることによって(または「c.company」と「c.customer」のようにcustomer-table(顧客c)で同じ方法を使用することによって、顧客を一意にします

編集2:更新されたコード。

    select c.company, count(*)
    from companyregister c
    left join history h on h.company = c.company
    where h.status = '2'
    and h.substatus = '0'
    and h.timestamp > '2012-01-01'
    and h.timestamp < '2012-02-01'
    group by c.company
    having (c.company = 'AAA')
    or (c.company = 'BBB')
    or (c.company = 'CCC')
    order by c.company

上記の両方のコードセットは、次の2つの行を生成します。AAA630 CCC 3020

BBBを表示したいのですが、履歴に行がないため表示されません。

4

1 に答える 1

1

customer テーブルで左結合を作成します。名前はわかりませんが、こんな感じです。

select c.company, count(h.customer)
from customer as  c
left join history as h on h.customer = c.customer
...

もう 1 つの方法は、カウント時に条件を使用することです。ステータスに加えて他に必要な条件があるかどうかはわかりませんが、次のようなものがあります。

select company, sum(case status when '2' then 1 else 0 end)  
from history
where substatus = '0'
and timestamp > '2012-01-01'
and timestamp < '2012-02-01'
and customer in ('AAA', 'BBB', 'CCC')
group by customer  
order by customer
于 2012-06-26T06:31:07.323 に答える