我有一個使用以下查詢創建的表
create table damaged_property_value
(case_id int, property_value varchar(100) );
insert into damaged_property_value (1,'2000'),(2,'5000,3000,7000');
問題是我需要找到所有被損壞的財產的總值。
我正在撰寫以下查詢以回傳總和:
select SUM(cast(property_value as unsigned)) from damaged_property_value;
它回傳總和為 7000,即 2000 5000。它沒有考慮用逗號分隔的財產的價值。
請注意,5000,3000 和 7000 是在特定情況下已損壞的三個不同屬性的值。它應該產生 17000 作為答案。
如何解決這個問題呢。
請幫忙!
uj5u.com熱心網友回復:
如前所述,最好的解決方案是修復資料結構。現在,只是為了解決問題的樂趣,經過大量研究,我設法執行以下操作(它要求 case_id 是順序的,從 1 開始)計算 property_value 字串的值并將它們放入新的 actual_value場地。
drop table if exists damaged_property_value;
create table damaged_property_value
(case_id int primary key, property_value varchar(100), actual_value int );
insert into damaged_property_value (case_id, property_value) values (1,'2000'),(2,'5000,3000,7000'),(3, '7000, 2000'),(4, '100,200,300,400,500,600');
drop procedure if exists Calculate_values;
DELIMITER $$
CREATE PROCEDURE Calculate_values()
BEGIN
DECLARE count INT;
SET count = 1;
label: LOOP
select
concat('update damaged_property_value set actual_value = ',
replace((select property_value from damaged_property_value where case_id = count), ",", " "),
' where case_id = ', count, ';')
into @formula;
#select @formula;
prepare stmt from @formula;
execute stmt;
deallocate prepare stmt;
SET count = count 1;
IF count > (select count(*) from damaged_property_value) THEN
LEAVE label;
END IF;
END LOOP label;
END $$
DELIMITER ;
CALL Calculate_values();
select * from damaged_property_value;
/* select SUM(actual_value) from damaged_property_value; */
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518124.html
標籤:mysql
