我可以从以下查询获得以下输出 -
SELECT
(
CASE
WHEN ta.Battery = 'HVA' THEN
'Huawei Valued Battery'
WHEN ta.Battery = 'HNVA' THEN
'Canibalized Battery'
WHEN ta.Battery = 'ZVA' THEN
'ZTE Valued Battery'
WHEN ta.Battery = 'ZNVA' THEN
'ZTE Canibalized Battery'
END
) AS Accessory_category,
COUNT(ta.Battery) Battery_count
FROM
tsc_accessory_details_for_repaired_and_qc_pass_phone_list ta
GROUP BY
ta.Battery,
ta.Battery
所以,我只需要在名为' cost'的结果表中添加另一列。是否有可能通过修改上述查询来获取输出。 例如:如果单位成本为' HVA'是100,总成本是700.如果单位成本为' ZVA'是200,3项的总费用是600.请建议我修改
我需要以下输出 -
答案 0 :(得分:1)
您可以为此添加另一个CASE
,但您可以这样做:
SELECT
sub.Value AS Accessory_category,
SUM(COALESCE(ta.UnitCost, sub.UnitCostValue, 0)) AS UnitCost,
COUNT(ta.Battery) Battery_count
FROM
tsc_accessory_details_for_repaired_and_qc_pass_phone_list ta
LEFT JOIN
(
SELECT 'HVA' Battery, 'Huawei Valued Battery' Value, 100 UnitCose, 700 AS UnitCostValue
UNION
SELECT 'HNVA', 'Canibalized Battery', 200, 600
UNION
SELECT 'ZVA', 'ZTE Valued Battery', 0, 0
UNION
SELECT 'ZNVA', 'ZTE Canibalized Battery', 0, 0
) AS sub ON ta.Battery = sub.Battery AND ta.unitCost = sub.UnitCost
GROUP BY
ta.Battery;
因此,您可以在子查询中列出所有值及其匹配,而不是这些case表达式,然后根据它进行连接。