因此我陷入了一个我试图解决的问题。我试着这么做 "选择最常见交货类型的描述"。 我执行它但我得不到回报。我甚至尝试使用传递类型ID替换计数,但即使这样我也没有收到任何输出。我做错了什么?
Select DeliveryTypeDescription
from DeliveryType
group by DeliveryTypeDescription
having count(*) >ALL(
Select count(*)
from DeliveryType
group by DeliveryTypeID)
答案 0 :(得分:4)
Select Top 1 DeliveryTypeDescription
From DeliveryType
Group By DeliveryTypeDescription
Order By count(*) Desc
答案 1 :(得分:0)
在您的情况下,交付类型将是主键,因此计数永远不会超过1?
IF OBJECT_ID('tempdb..#DeliveryType') IS NOT NULL DROP TABLE #DeliveryType
CREATE TABLE #DeliveryType (DeliveryTypeID INT,DeliveryType VARCHAR(20),DeliveryTypeDescription VARCHAR(200))
INSERT INTO #DeliveryType VALUES(101,'Home','Home Delivery'),(102,'Work','Work Delivery'),(103,'Ref','Deliver to Reference'),(104,'Pick','Pickup');
SELECT DeliveryTypeDescription FROM #DeliveryType GROUP BY DeliveryTypeDescription HAVING COUNT(*) > ALL ( SELECT COUNT(*) FROM #DeliveryType GROUP BY DeliveryTypeID);
在那种情况下,
SELECT COUNT(*)
FROM #DeliveryType
GROUP BY DeliveryTypeID
将返回所有1,1,1,1
答案 2 :(得分:0)
Select DeliveryTypeDescription
from DeliveryType
group by DeliveryTypeDescription
having **count(*)** **>**ALL(
**Select count(*)**
from DeliveryType
group by DeliveryTypeID)
您正在检索所有行,对吧?所以我认为你必须使用'> ='而不是''。
答案 3 :(得分:0)
好的,所以我想出了使用子查询解决这个问题的方法。我的问题首先是我没有考虑客户使用的最常见交付类型的关系。具有外键的相对表位于“客户纸张表”中。因此,我所要做的就是在“CustomerPaper”表中找到DeliverTypeID的最高计数。
SELECT DeliveryType.DeliveryTypeDescription FROM DeliveryType
INNER JOIN CustomerPaper
ON DeliveryType.DeliveryTypeID = CustomerPaper.DeliveryTypeID
GROUP BY DeliveryType.DeliveryTypeDescription
HAVING COUNT(CustomerPaper.DeliveryTypeID) >=ALL
(SELECT COUNT(customerpaper.DeliveryTypeID) FROM CustomerPaper GROUP BY CustomerPaper.DeliveryTypeID)