简体   繁体   English

SQL 根据其他列中的值计算

[英]SQL Calculation based on value in other column

could use some help with an SQL query...I have a table containing a number of columns.可以对 SQL 查询使用一些帮助...我有一个包含许多列的表。 See below sample:请参见下面的示例:

Organisation | Resoure1 | Resource2 | Type
A            |        1 |         4 | W
B            |        4 |         5 | L
C            |        4 |         6 | W
D            |        5 |         3 | W
E            |        4 |         2 | L
A            |        4 |         4 | L
C            |        3 |         5 | L

I have a query that reads from this table and inputs data in another table:我有一个从该表中读取并在另一个表中输入数据的查询:

INSERT INTO daily_totals 
(Organisation, Resource1, Resource2, Type) 
SELECT Organisation
     , sum(Resource1)
     , sum(Resource2)
     , SUM(CASE WHEN Type LIKE "W%" THEN 1 ELSE 0 END) 
  FROM db.mytable 
 GROUP 
    BY organisation;

However, I now need a small modification to the above part SUM(CASE WHEN Type LIKE "W%" THEN 1 ELSE 0 END) - column TYPE in total needs to be dependent on Resource1 - Odd numbers in Resource1 need to be rounded to nearest Even number and then halved.但是,我现在需要对上述部分SUM(CASE WHEN Type LIKE "W%" THEN 1 ELSE 0 END)进行小修改 - 列类型总共需要依赖于 Resource1 - Resource1 中的奇数需要四舍五入到最接近的值偶数再减半。 Therefore I need to do something like:因此我需要做类似的事情:

SUM(CASE WHEN Type LIKE "W%" THEN 1 ELSE 0 END) * CEILING(sum(CASE WHEN Resource1 = 1 THEN 2 ELSE Resource1 END) / 2 WHERE Type LIKE "W%")

But this results in syntax errors and I cannot figure out a way round it.但这会导致语法错误,我无法找到解决方法。

Can I get some help with the syntax?我可以在语法方面获得一些帮助吗?

Desired Output in table "Totals":表“总计”中所需的 Output:

Organisation | Resource1 | Resource2 | Type
A | 5 | 8 | 2
B | 4 | 5 | 0
C | 7 | 11 | 2
D | 5 | 3 | 3
E | 4 | 2 | 0

If I understand you correctly, what you want is this:如果我理解正确,你想要的是:

SUM(CASE WHEN Type LIKE 'W%' 
    THEN IF(Resource1 % 2 = 1, Resource1 + 1, Resource1) 
    ELSE 0
    END) / 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM