我有一个使用TOP 1子句(query2)的查询,我想加入另一个使用聚合函数的查询,但我不知道该怎么做。
我想要一个看起来像这样的结果查询:
"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
答案 0 :(得分: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
答案 1 :(得分:1)
这样的东西,只要每个子查询只返回一行,看起来就是这种情况,因为你的一个查询选择了前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