以下仿真表包含訂單明細,其中cust_nbr
代表訂單號。我試圖找到如果訂單中包含90000,我需要知道90000的價格是否大於其他項目加稅的總和。我在這張表中有數十萬條記錄。我正在使用Teradata。多聚合多過濾器單表SQL
CREATE TABLE Line_Item_Details_Tbl (
cust_nbr INT,
trn_dt DATE,
str_typ VARCHAR(6),
trn_nbr INT,
item_nbr INT,
price DECIMAL(6,2),
tax DECIMAL(6,2)
);
的樣本數據:
INSERT INTO Line_Item_Details_Tbl VALUES
(5551, '12/22/2011', 'store', 215, 12345, 10.00, 1.25);
INSERT INTO Line_Item_Details_Tbl VALUES
(5551, '12/22/2011', 'store', 215, 65715, 6.25, 0.75);
INSERT INTO Line_Item_Details_Tbl VALUES
(5551, '12/22/2011', 'store', 215, 90000, 40.00, 0);
INSERT INTO Line_Item_Details_Tbl VALUES
(6875, '12/10/2011', 'online', 856, 72345, 8.50, 1.00);
INSERT INTO Line_Item_Details_Tbl VALUES
(6875, '12/10/2011', 'online', 856, 65715, 6.25, 0.75);
INSERT INTO Line_Item_Details_Tbl VALUES
(3500, '12/12/2011', 'store', 402, 54123, 45.00, 4.00);
INSERT INTO Line_Item_Details_Tbl VALUES
(3500, '12/12/2011', 'store', 402, 90000, 20.00, 0);
INSERT INTO Line_Item_Details_Tbl VALUES
查詢應做到以下幾點:
Select cust_nbr, trn_dt, trn_nbr, sum(price + tax) as purchase
For a cust_nbr with str_typ = 'store' AND contains an item_nbr = 90000,
aggregate price + tax for all items related to cust_nbr except item_nbr 90000
因此,初步的結果應該是:
cust_nbr : trn_dt : trn_nbr : purchase
5551 12/22/2011 215 $18.25
3500 12/12/2011 402 $49.00
然後,對於每個記錄在初步結果,我需要減去的item_nbr
90000從purchase
,價格也只有當購買小於 的item_nbr
90000價格爲net_cb
所以返回結果,我的結局結果應該是:
cust_nbr trn_dt trn_nbr net_cb
5551 12/22/2011 215 ($21.75)
什麼是你的RDBMS? – 2011-12-31 06:41:09
@Michal我正在使用Teradata。 – 2011-12-31 06:44:58
@Donna:正確的[示例代碼](http://sscce.org/)(這裏是SQL語句)比任何ad hoc模式和示例數據格式更有用。請使用'CREATE TABLE'和'INSERT ... VALUES'作爲樣本。所需的結果不需要作爲示例代碼呈現,因爲結果是代碼的輸出,而不是代碼本身。 – outis 2011-12-31 07:48:01