gpt4 book ai didi

SQL Server - 获取排名第一的产品的总计数

转载 作者:行者123 更新时间:2023-12-02 16:50:28 24 4
gpt4 key购买 nike

我需要能够找到客户所下订单的总数,而且还需要在一次查询中找到排名靠前的产品。例如在下面的结构中,

CREATE TABLE #Cust (CustId INT, CustName VARCHAR(50))
CREATE TABLE #Product (ProductId INT, ProductName VARCHAR(10) )
CREATE TABLE #Orders (CustId INT, ProductId INT, OrderTaken BIT)

INSERT #Cust
( CustId, CustName )
VALUES ( 1, 'Paul' ),
( 2, 'F' ),
( 3, 'Francis' )

INSERT #Product
( ProductId, ProductName )
VALUES ( 1, 'Table' ),
( 2, 'Chair' )

INSERT #Orders
( CustId, ProductId, OrderTaken )
VALUES ( 1, 1, 1 ),
( 1, 1, 1 ),
( 1, 2, 1 ),
( 2, 1, 1 )

我提出了一个查询,

SELECT * FROM #Cust AS C OUTER APPLY 
(
SELECT TOP 1 SQ.ProductId, SUM(SQ.TotalCount) AS TotalQty FROM
(
SELECT O.ProductId, COUNT(*) TotalCount
FROM #Orders AS O WHERE O.CustId = C.CustId
GROUP BY O.CustId , O.ProductId
) SQ
GROUP BY SQ.ProductId
) X

但是,这并没有给我想要的结果,对于 Paul 来说,它给了我正确的 ProductId,但只是该产品的计数。

我想要返回一个查询,

CustId  |   CustName    |   ProductId   |   TotalQty
--------+---------------+---------------+------------
1 | Paul | 1 | 3
2 | F | 1 | 1
3 | Francis | NULL | NULL

最佳答案

一个选项是使用WITH TIES 子句

Select Top 1 with ties 
CustID
,CustName
,ProductId
,TotalQty
From (
Select C.CustID
,C.CustName
,O.ProductId
,TotalQty = count(O.CustId) over (Partition By O.CustID)
,ProdCount = count(O.CustId) over (Partition By O.CustID,O.ProductID)
From #Cust C
Left Join #Orders O on C.CustID=O.CustId
) A
Order by Row_Number() over (Partition By CustID Order by ProdCount Desc)

返回

CustID  CustName    ProductId   TotalQty
1 Paul 1 3
2 F 1 1
3 Francis NULL 0

关于SQL Server - 获取排名第一的产品的总计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42021577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com