私は各店舗の製品数/システム数を探しています。テーブルは次のようになります。テーブルを結合した後の元の数を取得するには?
Store
Id
100
200
Customer
Id | dealerId
1 | 100
2 | 200
System
Id | CustomerId
20 | 2
30 | 2
40 | 2
50 | 1
Product
Id | SystemId
1000 | 20
2000 | 50
は私が取得しようとしています:
storeId | Number of systems | number of products | average
100 | 1 | 1 | 1/1
200 | 3 | 1 | 1/3
私はこのクエリを書かれています。正しい数の製品を手に入れることができますが、私はテーブルに参加しているのでシステムの台数が狂っています。各店舗のシステムの合計数を得る方法はありますか?
SELECT
s.Id as Store,
COUNT(Distinct SystemsIden) as NumOfSystems,
COUNT(distinct ProductIden) as NumOfProduct,
CAST(COUNT(distinct ProductIden)as float)/CAST(COUNT(Distinct SystemsIden) as
float) as average
FROM
Store s
INNER JOIN
(
Select systemsiden,CustomerIden,ProductIden, Customer.StoreId as
storeiden from
(
select Product.ID as ProductIden, System.Id as systemsiden, System.customerId as CustomerIden from product join Ssystem On System.Id = Product.SystemIdId
)
table1 join Customer
on Customer.Id = CustomerIden
)
table2 On s.Id = storeiden
GROUP BY
s.Id
なぜ浮くためにあなたの数をキャストしていますか?小数点以下を使用してください。浮動小数点数はおおよそのデータ型です。 –
@あなたはmysqlまたはsql-serverのいずれかを使用している可能性があります。あなたのコードが本当に両方のデータベースで実行されなければ、実際の目的を果たさないので、あなたの質問から他のタグを削除してください。 –