如何计算每一行给定条件的总数?

时间:2016-06-14 13:46:21

标签: sql oracle

我有美元和欧元货币。

我想在最后一栏只计算欧元价格。

const redis = require('redis'),
      Promise = require('bluebird')

function getUser(id) {
  return redis.getAsync(id)
    .then(user => JSON.parse(user))
}

module.exports = () => {
  Promise.promisifyAll(redis.RedisClient.prototype)
  Promise.promisifyAll(redis.Multi.prototype)

  return new Promise((resolve, reject) => {
    const client = redis.createClient(REDIS_SERVER)
    client.on('connect', onConnect)
    client.on('error', err => {
      throw err
    })

    function onConnect() {
      return resolve({
        getUser
      })
    }
  })
}

示例,我只想要SELECT CUSTOMER, PRODUCT, PRICE, CURRENCY, FROM MORE.PRODUCTS WHERE CUSTOMER = '1000' CUSTOMER PRODUCT PRICE CURRENCY 1000 BIKE 100 € 1000 CAR 200 € 1000 BIKE 50 $ 1000 CANON 120 € 1000 TRAIN 300 $ €值:

SUM

最好的方法是什么?

我尝试在CUSTOMER PRODUCT PRICE CURRENCY TOTAL PRICE 1000 BIKE 100 € 420 1000 CAR 200 € 420 1000 BIKE 50 $ 420 1000 CANON 120 € 420 1000 TRAIN 300 $ 420 子句中使用子查询,但我无法使其工作。

2 个答案:

答案 0 :(得分:5)

使用analytic function计算总数:

SELECT CUSTOMER, 
       PRODUCT, 
       PRICE, 
       CURRENCY, 
       SUM( CASE CURRENCY WHEN '€' THEN PRICE END ) OVER () AS TOTAL_PRICE
FROM   MORE.PRODUCTS 
WHERE  CUSTOMER = '1000'

<强>输出

CUSTOMER PRODUCT PRICE CURRENCY TOTAL_PRICE
-------- ------- ----- -------- -----------
    1000 BIKE      100 €                420
    1000 CAR       200 €                420
    1000 BIKE       50 $                420
    1000 CANON     120 €                420
    1000 TRAIN     300 $                420

答案 1 :(得分:-3)

SELECT CUSTOMER, SUM(TOTAL_PRICE)  
FROM MORE.PRODUCTS 
WHERE CUSTOMER = '1000' and CURRENCY = '€'

您必须过滤欧元价格。