2011-11-18 56 views
2

我有一個查詢使用TOP 1子句(query2),我想加入到另一個查詢使用聚合函數,但我不知道如何去做。如何將使用top 1子句的查詢連接到使用聚合函數的查詢?

我想要得到的查詢,看起來像這樣:

"select Count(*), Avg(AmtSpent), TOP 1 (Outlet_Code)...." 

敬請指教。謝謝。

查詢1:

select Count(*), Avg(AmtSpent) from Transact Where CardNo In 
(Select CardNo from Card where MemberID = 'Mem003') 

查詢2:

select TOP 1 (Outlet_Code) from Transact where CardNo In 
(Select CardNo from Card where MemberID = 'Mem003') 
group by Outlet_Code 
Order by count(Outlet_Code) desc 

回答

1

這樣的事情,只要每個子查詢只返回一行,它看起來是這樣,因爲你的查詢之一正在選擇top 1,另一個沒有group by從句。這個工程在SQL Server 2008中

select TransactCount, TransactAvg, OutletCode 
from 
(

    select TOP 1 (Outlet_Code) as OutletCode 
    from Transact where CardNo In 
    (Select CardNo from Card where MemberID = 'Mem003') 
    group by Outlet_Code 
    Order by count(Outlet_Code) desc 


) rsOutletCode 
cross join 
(

    select Count(*) as TransactCount, Avg(AmtSpent) as TransactAvg 
    from Transact 
    Where CardNo In 
    (Select CardNo from Card where MemberID = 'Mem003') 

) rsTransact 
2

做的第一查詢和應用其他:

-- Temp tables for demo 
CREATE TABLE #Transact (
    ID INT PRIMARY KEY, 
    AmtSpent NUMERIC(18,2), 
    CardNo INT, 
    Outlet_Code VARCHAR(10) 
) 

CREATE TABLE #Card (
    CardNo INT PRIMARY KEY, 
    MemberID VARCHAR(10) 
) 

-- Some mock values 
INSERT #Card VALUES (1, 'Mem001') 
INSERT #Card VALUES (2, 'Mem002') 
INSERT #Card VALUES (3, 'Mem003') 
INSERT #Card VALUES (4, 'Mem004') 
INSERT #Card VALUES (5, 'Mem005') 
INSERT #Card VALUES (6, 'Mem006') 
INSERT #Card VALUES (7, 'Mem007') 
INSERT #Card VALUES (8, 'Mem008') 
INSERT #Card VALUES (9, 'Mem009') 

INSERT #Transact VALUES (1, 100.0, 1, 'Outlet 1') 
INSERT #Transact VALUES (2, 200.0, 1, 'Outlet 2') 
INSERT #Transact VALUES (3, 300.0, 2, 'Outlet 3') 
INSERT #Transact VALUES (4, 400.0, 2, 'Outlet 4') 
INSERT #Transact VALUES (5, 500.0, 3, 'Outlet 5') 
INSERT #Transact VALUES (6, 600.0, 8, 'Outlet 6') 
INSERT #Transact VALUES (7, 700.0, 9, 'Outlet 7') 

DECLARE @MemberID VARCHAR(10) 

SET @MemberID = 'Mem002' 

-- The query 
SELECT 
    COUNT(*) AS Count, 
    AVG(T.AmtSpent) AS Average, 
    _T.Outlet_Code 
FROM 
    #Transact T 

    INNER JOIN #Card C ON 
    T.CardNo = C.CardNo 

    OUTER APPLY (
     SELECT 
      TOP 1 Outlet_Code 
     FROM 
      #Transact _T 

      INNER JOIN #Card C ON 
      _T.CardNo = C.CardNo 
     WHERE 
      C.MemberID = @MemberID 
     GROUP BY 
      Outlet_Code 
    ) AS _T 
WHERE 
    C.MemberID = @MemberID 
GROUP BY 
    _T.Outlet_Code 

-- Clean up mock stuff 
DROP TABLE #Card 
DROP TABLE #Transact