基于mysql中的多列获取数据

时间:2014-12-10 10:07:57

标签: mysql

我有桌子公寓,桌子结构如下所示

      id    |   apid   |   bhk   |   facing  | size  |  units
       1    |     2    |    2    |    east   |  1200 |   20
       2    |     2    |    2    |    east   |  1500 |   40
       3    |     2    |    2    |    west   |  1300 |   30
       4    |     2    |    2    |   north   |  1400 |   10
       5    |     2    |    2    |   north   |  1500 |   30
       6    |     2    |    3    |    east   |  1100 |   25
       7    |     2    |    3    |    north  |  1000 |   40
       8    |     3    |    2    |     west  |  850  |   15
       9    |     3    |    2    |    south  |  970  |   20
       10   |     3    |    3    |    south  |  1200 |   35

我必须写一个查询,这样我必须得到输出为apid = 2,bhk = 2,facing = east,sum(units)= 60 and apid = 2,bhk = 2,facing = north,sum (单位)= 40

1 个答案:

答案 0 :(得分:0)

查询1:

select apid,bhk,facing,sum(units) from apartments where apid=2,bhk=2,facing = 'east'

查询2

select apid,bhk,facing,sum(units) from apartments where apid=2,bhk=2,facing = 'north'

最终查询:

    select apid,bhk,facing,sum(units) from apartments where apid=2,bhk=2,facing = 'east'

UNION 

    select apid,bhk,facing,sum(units) from apartments where apid=2,bhk=2,facing = 'north'