Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Order by和top 1在我的代码中不起作用,它们只是计数_Sql_Sql Server_Count_Sql Order By - Fatal编程技术网

SQL Order by和top 1在我的代码中不起作用,它们只是计数

SQL Order by和top 1在我的代码中不起作用,它们只是计数,sql,sql-server,count,sql-order-by,Sql,Sql Server,Count,Sql Order By,因此,我的任务是找到在Northwind发送最多产品的供应商ID。这是我的密码 select s.SupplierID, count(p.ProductID) from Suppliers s join Products p on s.SupplierID = p.SupplierID group by s.SupplierID having count(p.ProductID) in (select top 1 count(p.ProductID) from Products order

因此,我的任务是找到在Northwind发送最多产品的供应商ID。这是我的密码

select s.SupplierID, count(p.ProductID) 
from Suppliers s join Products p
on s.SupplierID = p.SupplierID
group by s.SupplierID
having count(p.ProductID) in 
(select top 1 count(p.ProductID)
from Products
order by count(p.ProductID) desc) 

但是我得到的是我的结果,他们只是在没有前1的情况下计数,而order by不起作用

在子查询中需要一个
分组依据

having count(p.ProductID) in (select top 1 count(p.ProductID)
                              from Products
                              group by SupplierID
                              order by count(p.ProductID) desc
                             ) 
但是,更简单的公式使用窗口函数:

select top (1) p.SupplierID, count(*) as cnt,
from products p 
group by p.SupplierID
order by count(*) desc;
请注意,您不需要
供应商
,因为
id
已经在
产品
中,并且您没有选择任何其他列


此外,如果您希望在出现结时有多行,您可能需要选择带结的顶部(1)。

在子查询中需要一个
分组依据

having count(p.ProductID) in (select top 1 count(p.ProductID)
                              from Products
                              group by SupplierID
                              order by count(p.ProductID) desc
                             ) 
但是,更简单的公式使用窗口函数:

select top (1) p.SupplierID, count(*) as cnt,
from products p 
group by p.SupplierID
order by count(*) desc;
请注意,您不需要
供应商
,因为
id
已经在
产品
中,并且您没有选择任何其他列


此外,如果您希望在出现领带的情况下有多行,您可能希望
选择带领带的顶部(1)。

我只需要使用
排序和
顶部

select top (1) s.SupplierID, count(*) cnt
from Suppliers s 
join Products p on s.SupplierID = p.SupplierID
group by s.SupplierID
order by cnt desc

如果您想允许使用ties,请使用带有ties的
top(1)

我只会使用
ORDER BY
top

select top (1) s.SupplierID, count(*) cnt
from Suppliers s 
join Products p on s.SupplierID = p.SupplierID
group by s.SupplierID
order by cnt desc

如果您想允许绑定,请使用带有绑定的
top(1)

您使用的是MySQL还是MS SQL Server?(该查询无法同时在这两个服务器上运行…)您使用的是MySQL还是MS SQL Server?(该查询不会同时对这两个…)