SQL - 条件“分组依据”

时间:2017-04-13 20:02:06

标签: sql group-by

我有一张表与客户,他们的帐户金额和相应的货币。我需要选择帐户中金额最高的100个客户,只考虑2种货币(美元和欧元) - >所有金额已经以美元换算。这是我表的摘录:

client |  amount | currency
1      |  100    |  USD
2      |  20     |  HKD
3      |  50     |  EUR
1      |  15     |  EUR

我只对美元和欧元感兴趣,我必须保留每种货币的金额,并根据这两种货币的总金额对客户进行排名。上表所需的输出如下:

client |  amount in USD |  amount in EUR | total value
1      |  100           |  15            | 115
3      |  0             |  50            | 50

任何帮助将不胜感激! 干杯, 拉法

3 个答案:

答案 0 :(得分:1)

使用条件聚合(例如在Sql Server中):

select 
    client
  , sum(case when currency = 'USD' then amount else 0 end) as AmountInUSD
  , sum(case when currency = 'EUR' then amount else 0 end) as AmountInEUR
  , sum(case when currency in ('USD','EUR') then amount else 0 end) as TotalValue
from t
group by client
having sum(case when currency in ('USD','EUR') then amount else 0 end) > 0
order by TotalValue desc

rextester演示(对于sql server):http://rextester.com/LJF89562

返回:

+--------+-------------+-------------+------------+
| client | AmountInUSD | AmountInEUR | TotalValue |
+--------+-------------+-------------+------------+
|      1 |         100 |          15 |        115 |
|      3 |           0 |          50 |         50 |
+--------+-------------+-------------+------------+

答案 1 :(得分:0)

您可以将CASE表达式与group by client一样使用

sum(case when currency = 'USD' then amount) as amount in USD 

答案 2 :(得分:0)

假设您的表名是“客户”:

    SELECT 
    client, 
    SUM(CASE c.currency WHEN 'USD' THEN c.amount ELSE 0 END) AS amount_in_usd,
    SUM(CASE c.currency WHEN 'EUR' THEN c.amount ELSE 0 END) AS amount_in_eur,
    SUM(amount) AS total_value
    FROM clients AS c
    WHERE c.currency = 'USD' OR c.currency='EUR'
    GROUP BY c.client
    ORDER BY total_value DESC