[英]SQL Server 2012 Query
I have two tables. 我有两张桌子。 The one is products
and the other is suppliers
. 一个是products
,另一个是suppliers
。 The table products
has product_id
, product_price
, product_name
, supplier_id
and category_id
columns. 该表products
已经product_id
, product_price
, product_name
, supplier_id
和category_id
列。 The supplier_id
is the foreign key from suppliers
table and the product_id
is the primary key. 该supplier_id
是国外关键suppliers
表和product_id
是主键。 The suppliers
table has supplier_id
, supplier_name
, state
and city
columns. suppliers
表具有supplier_id
, supplier_name
, state
和city
列。 The query that I want to make is "select full details of the supplier with the largest number of products." 我要进行的查询是“选择产品数量最多的供应商的完整详细信息”。 I was thinking something like this: 我在想这样的事情:
SELECT * FROM suppliers INNER JOIN products ON suppliers.supplier_id=products.supplier_id;
but I dont know how to count every supplier's products. 但是我不知道如何计算每个供应商的产品。 Any ideas? 有任何想法吗? Thanks is advance. 感谢是前进。
Don't join. 不要参加 You want data from the suppliers table where a certain condition (largest number of products) is given. 你想从 那里一定条件(产品数量最多)给出的供应商表数据。 Hence suppliers
in the FROM
clause, products
in the WHERE
clause. 因此, suppliers
在FROM
子句中, products
将在WHERE
子句。
You'd group the products
table by supplier_id
, so as to get an aggregate per supplier. 你组的products
由表supplier_id
,这样才能得到每个供应商的总和。 Order by count and take the top record(s). 按计数排序并取得最高记录。
select *
from suppliers
where supplier_id in
(
select top(1) with ties
supplier_id
from products
group by supplier_id
order by count(*) desc
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.