2017-08-02 147 views
1

我的數據是建立在以下方式:條件求和並計數的Teradata(SQL幫助)

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 

但是,我當前的查詢是單獨檢查每個行項目,而不是在帳戶級別。

我該怎麼辦?

+4

在哪裏查詢?它是MySQL還是SQL Server?不能兼而有之。請正確標記。 – Eric

+0

閾值信息存儲在哪裏? –

+0

閾值信息必須作爲條件添加到查詢中。 –

回答

0

在標準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; 
+0

我希望將閾值應用於每個人的帳戶級別總和,然後顯示出人員,帳戶收入超過閾值總和的總和以及這些帳戶的計數 –

0

下面的查詢將通過人/區域聚集,然後才能產生結果應用於從單獨的表區域的閾值。

更新,考慮單獨區域的閾值

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 
+0

不同地域的不同閾值如何?例如。 AU爲500,CH爲200?我該如何照顧? –

+0

取決於閾值的來源。我只需加入區域閾值表的「T」表來替換@Threshold變量。我會更新答案,舉例說明我的意思是 –

+0

已更新。希望有所幫助! –