I would like to calculate the same column called value
in one table called table_name
:
CREATE TABLE IF NOT EXISTS Table_Name(
Code VARCHAR(20) COMMENT 'Code',
Date COMMENT 'Date',
Value DECIMAL(25,2) COMMENT 'Value',
Remark STRING COMMENT 'Value type, "111, 222, or 333 etc"',
supposed I need to calculate "(value's type = 111 or 222 or 333)/(value's type = 444)" between 20180201 and 20180228, and I use SQL query as below:
select t.code,t.date,t.remark,t1.value/t2.value as val
from table_name t
right join (
select sum(t.value) fzqsz, t.code from table_name t
WHERE remark = '111' OR remark = '222' OR remark = '333'
group by t.code,t.date
) t1 on t.code = t1.code
left join (
select sum(t.value) value,t.code from table_name t
WHERE remark = '444'
group by t.code,t.date
) t2 on t1.code = t2.code
-- if I put below line in `SQL query` I get nothing(0 results)
-- where t.code='00001' and t.date >='20180201' and date <= '20180228'
I only select remark="111 or 222 or 333", I don't know why all remarks("555 and 666") appeared, I got results as below:
code date remark val
1 00001 2018-02-25 00:00:00.0 111 0.00002929
2 00001 2018-02-25 00:00:00.0 222 0.00002977
3 00002 2018-02-25 00:00:00.0 333 0.00002917
4 00003 2018-02-25 00:00:00.0 444 0.00002987
3 00001 2018-02-25 00:00:00.0 555 0.00002917
4 00002 2018-02-25 00:00:00.0 666 0.00002987
Is the SQL query right? I'm sure there is some problem with my SQL query. Really appreciated with any advice.
I don't know why all remarks("555 and 666") appeared
. They do, because there is no restriction. You are selecting all t witht.code='00001' and t.date >='20180201' and date <= '20180228'
. What surprises me hence is why there are code '00002' and '00003' in your results. This is weird and shouldn't be possible with the query you are showing. – Thorsten Kettner