结果数据集中的SQL Case表达式问题

时间:2019-05-14 23:10:54

标签: sql sql-server case

  echo '<div class="col-xs-6 col-md-2 col-md-push-8 social-buttons">
  <div class="row">

          <a class="pull-right" href="'. $instance['facebook'] .'" target="_blank">
            <span class="icon-facebook-icon"></span>
          </a>
          <!--<a class="pull-right" href="'. $instance['tripadvisor'] .'" target="_blank">
            <span class="icon-tripadvisor-icon"></span>
          </a>-->
          <a class="pull-right" href="'. $instance['twitter'] .'" target="_blank">
            <span class="icon-twitter-icon"></span>
          </a>

  </div>
  <div class="row pull-right terms-links">
    <ul>
      <li><a href="'. $instance['tac-url'] .'">Terms</a></li>
      <li><a href="'. $instance['priv-url'] .'">Privacy</a></li>
      <li><a href="'. $instance['sitemap-url'] .'">Sitemap</a></li>
    </ul>
  </div>
</div>';

此SQL查询返回以下结果集:

SELECT  
    b.Product_Code,
    b.Account_Id,
    b.Channel_Desc,
    r.Min_Range, r.Max_Range,
    b.Balance AS openingbalance,
    CASE 
       WHEN b.Balance > r.Max_Range
          THEN r.Max_Range - r.Min_Range
          ELSE b.Balance - r.Min_Range
    END AS Split_Balance,
    (CASE 
        WHEN b.Balance > r.Max_Range THEN r.Max_Range - r.Min_Range
        ELSE b.Balance - r.Min_Range
     END) / balance AS weighted_Avg
FROM 
    [EDH_DM_PRD].[dbo].[DataMart_Deposit] AS b
JOIN 
    [DBStats].[dbo].[Split_balances] AS r ON b.Product_Code = r.Product_Code 
                                          AND b.Channel_Desc = r.Channel_Desc
                                          AND b.Asat_Dt = '20190131'
                                          AND b.Acct_Status_Desc  = 'Open'
                                          AND b.Balance >= 0 
                                          AND b.Product_Code = '2000-0100'
                                          AND b.Channel_Desc = 'Broker BDMs'
                                          AND b.Account_Id = '31179111'
ORDER BY 
    Account_Id, Channel_Desc, Min_Range

在结果集中,“ openingbalance”应仅在第一行上指定。 其余行应将“ openbalance”显示为0。

1 个答案:

答案 0 :(得分:0)

您没有指定要使用的RDBMS,但是需要CASE WHEN 1 == ROW_NUMBER() OVER (...) THEN b.Balance ELSE 0 END或您的数据库支持的等效项。

要确定OVER子句中确切包含的内容,您必须更清楚地指定“第一”行是什么。如果从字面上看是指第一行,则可以只使用OVER (ORDER BY Account_Id,Channel_Desc,Min_Range),但这可能不是您想要的。