如何使用MySQL在单个查询中运行两个不同的查询?

时间:2016-08-04 11:16:50

标签: php mysql unions

我有一个包含这些列的Invoice表。

<section ng-controller="ArticlesController">
  <div class="page-header">
    <h1>Neue Evaluierung</h1>
  </div>
  <div class="col-md-12">
    <form name="articleForm" class="form-horizontal" ng-submit="create(articleForm.$valid)" novalidate>
      <fieldset>

        <div class="row form-group">
         <h3>Projekttitel</h3><input type="submit" class="btn btn-default btn-lg btn-success">
        </div>
        <div ng-show="error" class="text-danger">
          <strong ng-bind="error"></strong>
        </div>

        <input name="title" type="text" ng-model="title" id="title" class="form-control">

        <div ng-repeat="alert in alerts">

          <h3>{{alert.someTitle}}</h3>
          <input type="number" ng-model="alert.value"/>

          <div>
            <rzslider rz-slider-model="alert.value"
                      rz-slider-options="alert.options"></rzslider>
          </div>

          <br>
          <br>
          <br>
          <br>

          <div>
            <h4>{{alert.someweightTitle}}</h4>
            <input type="number" ng-model="alert.weight"/>
            <div>
              <md-slider flex md-discrete ng-model="alert.weight" step="1" min="1" max="100" aria-label="rating"></md-slider>
            </div>
          </div>

          <input type="number" ng-model="index"/>
          <input type="number" ng-model="indexdynamic"/>

        </div>


      </fieldset>
    </form>
  </div>
</section>

我希望按月获得美国总金额,非美国总金额组,我使用这些查询我只获得美国总金额

id total date         country
1   50   2016-01-25   USA
2   40   2016-01-24   UK
3   30   2016-01-22   France
4   40   2016-01-26   UK
5   50   2016-01-18   USA
6   60   2016-02-20   USA
7   70   2016-02-21   USA
8   55   2016-02-18   UK
9   75   2016-02-19   France

我得到了这个结果

SELECT MONTH(date),YEAR(date),SUM(total) as usa_amount 
FROM Invoice 
WHERE YEAR(date) = '2016' 
  AND country='USA' 
GROUP BY MONTH(date)

我想使用mysql工会或其他什么来获得这个结果?

MONTH(date)  YEAR(date)   usa_amount
01            2016         100
02            2016         130

1 个答案:

答案 0 :(得分:0)

case

中使用sum()
SELECT MONTH(date),
       SUM(case when country =  'USA' then total else 0 end) as usa_amount,
       SUM(case when country <> 'USA' then total else 0 end) as non_usa_amount 
FROM Invoice 
WHERE YEAR(date) = 2016
GROUP BY MONTH(date)