做的第一查詢和應用其他:
-- 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