【问题标题】:sql server select value depend by datesql server 选择值取决于日期
【发布时间】:2017-08-03 08:17:27
【问题描述】:

我有 2 张桌子:

  1. 文件

    (docId | date | value | currencyid | currencyRate | netvalue )
    1 | 2017/07/30 | 777 | EUR | 4.55 | 150.66
    2 | 2017/07/30 | 456 | EUR | 4.55 | 100.00
    3 | 2017/07/29 | 440 | RON | 1.00 | 440.00
    4 | 2017/07/28 | 999 | RON | 1.00 | 999.00
    
  2. 汇率

    (only for currencyid = EUR)
    (date | currencyRate)
    2017/07/30 | 4.55
    2017/07/29 | 4.53
    2017/07/28 | 4.48
    

我需要按月提取所有文件的欧元总额。我的问题是当我尝试将本地值(RON)从documents.value 转换为EURO 时。

文档中的示例 1:当 currencyid = EUR 时,净值自动从 value/currencyRate 计算(在文档中),只有我需要提取documents.netvalue

问题是:

文档中的示例 2:当 currencyid = RON 时,净值以 RON 表示,我需要将其转换为 EURO 与制造日期(非当前日期)的值。因此,我需要从 currencyrates 表中提取每个日期的 currencyRate 并在 CASE 中使用它来划分值(以 RON 为单位)。

和我的查询:

SELECT 
     p.name Client, year(d.date) AS Year, month(d.date) AS Month, CONVERT(DECIMAL(10,2),d.CurrencyNetValue) CurrencyNetValue, d.CurrencyId, 
     CASE 
        WHEN d.CurrencyId = 1 THEN d.CurrencyNetValue/(select top 1(c.CurrencyRate) from CurrencyRates c inner join documents d on d.date=c.date where c.CurrencyId=2)
        WHEN d.CurrencyId = 2 THEN d.CurrencyNetValue
     END 
     AS EuroNetValue
     FROM documents d
     inner join partners p ON d.partnerid = p.partnerid
     WHERE d.doctypeid = 200
     ORDER BY d.date DESC

错误出现在子查询中,我尝试在创建日期返回 currencyRate 的值。我只需要返回一个数字,而不是所有列

【问题讨论】:

  • 感谢 diiN。这是问题:THEN d.CurrencyNetValue/(select top 1(c.CurrencyRate) from CurrencyRates c inner join documents d on d.date=c.date where c.CurrencyId=2)。我知道前 1 不正确,但只需要返回一个值 ...
  • 在您的currencyrates 表中,您会在同一日期有多个条目吗?如果没有,如果您从外部查询加入d.date,则没有理由在子查询中需要top 函数:select c.CurrencyRate from CurrencyRates c where c.date=d.date and c.CurrencyId=2
  • 不,我每天只有一个条目。我每天有 4 种货币(USD、EUR、GBR、RON),但我的条件是 currencyid = 2(只有 EUR)。货币汇率中的每一行都记录一个值。 EUR 的一行,GBR 的一行,USD 的一行。我只需要 EUR 的行,但是这个查询返回了 EURO 的所有值。我只需要具体的日期
  • 您是否尝试像我之前的评论那样编写子查询?

标签: sql date join


【解决方案1】:

已解决:

需要为新“表”添加内连接

inner join (select * from CurrencyRates where CurrencyId = 2) as cr on d.Date = cr.Date

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2010-12-10
    • 2016-11-29
    • 2017-05-04
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多