以下模拟表包含订单详细信息,其中cust_nbr
表示订单号。我正在尝试查找订单是否包含item_nbr
90000,我需要知道 90000 的价格是否大于其他项目加税的总和。我在这张表中有数十万条记录。我正在使用 Teradata。
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
然后,对于初步结果中的每条记录,我需要从结果中减去 90000 的价格,item_nbr
只有purchase
当购买低于item_nbr
90000 的价格时才返回结果为net_cb
所以,我的最终结果应该是:
cust_nbr trn_dt trn_nbr net_cb
5551 12/22/2011 215 ($21.75)