我的数据按以下方式设置:
Person Account Revenue Region
A W 100 AU
A W 200 AU
A W 300 AU
B X 200 AU
B X 50 CH
B X 50 CH
以下是示例数据的代码:
IF OBJECT_ID('tempdb..#StackTest') IS NOT NULL
DROP TABLE #StackTest;
CREATE TABLE #StackTest
(Person varchar(1)
, Account varchar(1)
, Revenue int
, Region varchar(2));
INSERT INTO #StackTest
(Person
, Account
, Revenue
, Region)
VALUES
('A', 'W', 100, 'AU'),
('A', 'W', 200, 'AU'),
('A', 'W', 300, 'AU'),
('B', 'X', 200, 'AU'),
('B', 'X', 50, 'CH'),
('B', 'X', 50, 'CH');
我需要编写一个SQL查询,当帐户Q的总和超过Y时,只对那些帐户的收入求和。同样,当帐户Q的总和超过Y时,我还需要只统计那些帐户。所以如果我的话区域AU的总和阈值是500,区域CH的总和阈值是200,那么我想要以下输出
Output # of accounts exceeding threshold sum Revenue from these accounts
A 1 600
B 0 0
但是,我当前的查询是单独检查每个订单项,而不是在帐户级别。
我该怎么办?
答案 0 :(得分:1)
在标准SQL中,您将使用两个级别的聚合。我怀疑查询是这样的:
select person,
sum(case when region = 'AU' and revenue > 500 then 1
when region = 'CH' and revenue > 200 then 1
else 0
end) as numAccounts,
sum(case when region = 'AU' and revenue > 500 then revenue
when region = 'CH' and revenue > 200 then revenue
else 0
end) as reveue,
from (select person, region, sum(revenue) as revenue
from t
group by person, region
) t
group by person;
答案 1 :(得分:1)
以下查询将按人/地区汇总,然后应用单独表格中的区域阈值以生成结果。
更新以考虑单独的区域阈值
IF OBJECT_ID('tempdb..#Thresholds') IS NOT NULL
DROP TABLE #Thresholds
CREATE TABLE #Thresholds (Region VARCHAR(2), Revenue INT)
INSERT #Thresholds VALUES ('AU', 500), ('CH', 200)
--DECLARE @Threshold INT = 500
SELECT
T.Person,
SUM(CASE WHEN T.[Revenue] >= Thresholds.Revenue THEN T.[Count] ELSE 0 END) AS [# of accounts exceeding threshold sum],
SUM(CASE WHEN T.[Revenue] >= Thresholds.Revenue THEN T.[Revenue] ELSE 0 END) AS [Revenue from these accounts]
FROM (
SELECT
Person,
Region, -- Add region to apply thresholds by region
COUNT(DISTINCT Account) AS [Count],
SUM(Revenue) AS [Revenue]
FROM #StackTest
GROUP BY Person, Region
) T
INNER JOIN #Thresholds Thresholds
ON Thresholds.Region = T.Region
GROUP BY Person
ORDER BY Person