【问题标题】:Math beetween 2 selects in sqlsql中2个选择之间的数学
【发布时间】:2018-01-23 14:26:13
【问题描述】:

我正在为一个 c# 应用程序做一个简单的任务,我想用 SQL 来做所有的数学运算。

我有 1 个名为 xx_MainOeuvre 的表,我对其执行 2 次选择。 :

select xx_TypeMO, xx_pu from xx_MainOeuvre mo 
where mo.xx_TypeDuree != 1 and mo.xx_pu != 0 
and xx_sysParentId like 'CC1500107'

给我这个:

xx_TypeMO   |   xx_pu   |
==========================
MOI         |     45    |
MOV         |     34    |
MOE         |     50    |

select xx_TypeMO, sum(xx_Duree) as TimeSpend
from xx_MainOeuvre
where xx_TypeDuree = 1 and xx_sysParentId like 'CC1500107'
group by xx_TypeMO

女巫给了我这个:

xx_TypeMO   |   TimeSpend   |
=============================
MOI         |     4         |
MOV         |     12        |

xx_pu 是单价

我想要一个 timeSpend * unitPrice 的结果。

像这样:

xx_TypeMO   |   RealPrice    |
==============================
MOI         |     180 (4*45) |
MOV         |     408 (12*34)|

可以这样做吗?还是我应该继续使用我的 C# 方法?

谢谢。

【问题讨论】:

  • 你的预期输出是什么?
  • @Ravi 我已经添加了预期的输出
  • 我个人会收集所有数据并在 C# 中进行计算,因为如果您收集所有数据,您可以在程序的其他地方执行其他计算

标签: c# mysql sql


【解决方案1】:

您可以通过一个更简单的查询来做到这一点:

select xx_TypeMO,
       (sum(case when xx_TypeDuree = 1 then xx_Duree else 0 end) *
        sum(mo.xx_TypeDuree <> 1 and mo.xx_pu <> 0 )
       )
from xx_MainOeuvre
where xx_sysParentId like 'CC1500107'
group by xx_TypeMO

【讨论】:

  • 谢谢,我稍微修改了一下,效果很好。
【解决方案2】:

您可以为此使用子查询。像这样的东西(虽然我没有测试过):

SELECT mo1.xx_TypeMO,
    mo1.xx_pu * mo2.timeSpend AS RealPrice
FROM xx_MainOeuvre mo1
LEFT JOIN
(
    SELECT xx_TypeMO,
        SUM(xx_Duree) AS timeSpend
    FROM xx_MainOeuvre
    WHERE xx_TypeDuree = 1
    GROUP BY xx_TypeMO
) mo2 ON mo1.xx_TypeMO = mo2.xx_TypeMO
    AND mo1.xx_sysParentId = mo2.xx_sysParentId
WHERE mo1.xx_TypeDuree != 1 AND mo1.xx_pu != 0 
    AND xx_sysParentId = 'CC1500107'

【讨论】:

  • 谢谢,我稍微修改了一下,效果就像一个 Charm。
【解决方案3】:

感谢这两个答案(我稍作修改)我有 2 个有效的查询:

SELECT mo1.xx_TypeMO,
    xx_pu * timeSpend AS RealPrice FROM xx_MainOeuvre mo1 LEFT JOIN (
    SELECT xx_TypeMO,
        SUM(xx_Duree) AS timeSpend
    FROM xx_MainOeuvre
    WHERE xx_TypeDuree = 1 and xx_sysParentId like 'CC1500107'
    GROUP BY xx_TypeMO ) mo2 ON mo1.xx_TypeMO = mo2.xx_TypeMO
    AND mo1.xx_sysParentId = xx_sysParentId WHERE mo1.xx_TypeDuree != 1 AND mo1.xx_pu != 0 
    AND xx_sysParentId = 'CC1500107'

    select xx_TypeMO, sum(case when xx_TypeDuree = 1 then xx_Duree else 0 end) * sum(mo.xx_pu)
from xx_MainOeuvre mo
where xx_sysParentId like 'CC1500107'
group by xx_TypeMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    相关资源
    最近更新 更多