2017-03-25 4 views
3

は、私はテーブルがあるとし、さまざまな条件によって集計同じ列受注SQL - 次のようになります

|country| customer_id | order_id | 
| CA | 5   |  3 | 
| CA | 5   |  4 | 
| CA | 6   |  5 | 
| CA | 6   |  6 | 
| US | 2   |  7 | 
| US | 7   |  8 | 
| US | 7   |  9 | 
| US | 7   | 10 | 
| US | 2   | 11 | 

と私は

| country | customers_w_2_orders | customers_w_2_plus_orders | 
| CA  | 2     | 0       | 
| US  | 1     | 1       | 
、ようにテーブルを移入するクエリを作成したいです

ここでは、2つの注文を持つ顧客の数と3つの注文を持つ顧客の数を国別に集計します。ここで

は私がやったことだし、それは私が望む結果が得られませんでした。..

SELECT country, count(*) as cnt1, count(*) as cnt2 
FROM Orders 
GROUP BY country 
HAVING cnt1=2 AND cnt2>2; 

答えて

2
declare @orders table (country char(2), customer_id int, order_id int); 
insert into @orders values 
('CA', 5, 3), 
('CA', 5, 4), 
('CA', 6, 5), 
('CA', 6, 6), 
('US', 2, 7), 
('US', 7, 8), 
('US', 7, 9), 
('US', 7, 10), 
('US', 2, 11); 

select country, 
     sum(case when num_orders <= 2 then 1 else 0 end) as cust_w_2_orders, 
     sum(case when num_orders > 2 then 1 else 0 end) as cust_2_plus_orders 
from (
     select country, customer_id, count(*) num_orders 
     from @orders 
     group by country, customer_id 
    ) x 
group by country; 
GO 
 
country | cust_w_2_orders | cust_2_plus_orders 
:------ | --------------: | -----------------: 
CA  |    2 |     0 
US  |    1 |     1 

dbfiddle here

+0

ウィルOPが望むフォーマットを取得しないでください。スパーステーブルを作成します。 –

+0

あなたが提供したクエリは0.5msで終了し、他の回答よりも勝っています。ありがとう! – Manto

+0

私は助けてくれるのがうれしいです。 – McNets

1

まずテーブルを構築それあなたは、派生テーブルの上にグループ化することによって、number_of_ordersが2よりも2以上の頻度を数えることができる彼らは、各行が今country, customer_id, number_of_orders

ある国ごとに持っているすべての顧客と注文の#が含まれてい

select country, sum(num_orders = 2), sum(num_orders > 2) 
from (
    select country, customer_id, count(*) as num_orders 
    from Orders 
    group by country, customer_id 
) t group by country 
1
SELECT country, 
     (select count(distinct(customer_id)) from Orders o where o.country = Orders.country and (select count(*) from Orders o2 where o2.country = orders.country and o2.customer_id = o.customer_id) = 2) as customers_w_2_orders, 
     (select count(distinct(customer_id)) from Orders o where o.country = Orders.country and (select count(*) from Orders o2 where o2.country = orders.country and o2.customer_id = o.customer_id) > 2) as customers_w_2_plus_orders 
    FROM Orders 
GROUP BY country; 
関連する問題