我正在尝试根据产品代码(不同的代码获得不同的折扣)来计算帐户的折扣费用。 我正在努力寻找一种方法,可以修改查询,以便在一个查询中为我提供正确的结果,而不是多次运行同一查询并更改折扣和产品代码。
作为一个例子 如果代码是AmazonEC2,则对费用应用5% 如果代码是AmazonS3,则对费用应用3%, 否则,其余的要加1%。
SELECT line_item_usage_account_id
,sum(line_item_unblended_cost) AS cost
,sum(line_item_unblended_cost * 0.05) AS discounted_cost
,sum(line_item_usage_amount) AS usage
,CAST(line_item_usage_start_date AS DATE) AS start_day
,CAST(line_item_usage_end_date AS DATE) AS end_day
,line_item_product_code
FROM cost_management
WHERE line_item_usage_account_id IN ('330')
AND line_item_usage_start_date BETWEEN DATE '2019-03-01'
AND DATE '2019-10-01'
AND line_item_product_code = 'AmazonEC2'
GROUP BY line_item_usage_account_id
,CAST(line_item_usage_start_date AS DATE)
,CAST(line_item_usage_end_date AS DATE)
,line_item_product_code
HAVING sum(line_item_blended_cost) > 0
ORDER BY line_item_usage_account_id
答案 0 :(得分:2)
在Case
子句中使用Select
语句,
CASE
WHEN line_item_product_code = 'AmazonEC2'
THEN sum(line_item_unblended_cost * 0.05)
WHEN line_item_product_code = 'AmazonS3'
THEN sum(line_item_unblended_cost * 0.03)
ELSE sum(line_item_unblended_cost * 0.01)
END As discounted_cost
答案 1 :(得分:0)
请参阅“选择”中的“案例”列
SELECT line_item_usage_account_id,
SUM(line_item_unblended_cost) AS cost,
SUM(line_item_unblended_cost * 0.05) AS discounted_cost,
SUM(line_item_usage_amount) AS usage,
CAST(line_item_usage_start_date AS DATE) AS start_day,
CAST(line_item_usage_end_date AS DATE) AS end_day,
line_item_product_code,
CASE WHEN line_item_product_code = 'AmazonEC2'
THEN SUM(line_item_unblended_cost * 0.05)
WHEN line_item_product_code = 'AmazonS3'
THEN SUM(line_item_unblended_cost * 0.03)
ELSE SUM(line_item_unblended_cost * 0.01)
END discounted_cost2
FROM cost_management
WHERE line_item_usage_account_id IN ('330')
AND line_item_usage_start_date BETWEEN date '2019-03-01' AND date '2019-10-01'
AND line_item_product_code ='AmazonEC2'
GROUP BY line_item_usage_account_id, CAST(line_item_usage_start_date AS DATE), CAST(line_item_usage_end_date AS DATE), line_item_product_code
HAVING sum(line_item_blended_cost) > 0
ORDER BY line_item_usage_account_id
答案 2 :(得分:0)
如果您想要每个帐户每天 或每个帐户的信息,那么我认为您不希望line_item_product_code
中的GROUP BY
在这种情况下,您需要条件聚合:
SELECT line_item_usage_account_id,
SUM(line_item_unblended_cost) AS cost,
SUM(CASE WHEN line_item_product_code = 'AmazonEC2'
THEN line_item_unblended_cost * 0.05
WHEN line_item_product_code = 'AmazonS3'
THEN line_item_unblended_cost * 0.03
ELSE ine_item_unblended_cost * 0.01
END) As discounted_cost
SUM(line_item_usage_amount) AS usage,
CAST(line_item_usage_start_date AS DATE) AS start_day,
CAST(line_item_usage_end_date AS DATE) AS end_day
FROM cost_management cm
WHERE line_item_usage_account_id IN ('330') AND
line_item_usage_start_date BETWEEN DATE '2019-03-01' AND DATE '2019-10-01'
GROUP BY line_item_usage_account_id,
CAST(line_item_usage_start_date AS DATE),
CAST(line_item_usage_end_date AS DATE)
HAVING sum(line_item_blended_cost) > 0
ORDER BY line_item_usage_account_id