多个选择查询,其中多个条件在MySQL上

时间:2017-04-09 21:23:41

标签: mysql select

我的工作查询是;

SELECT SUM(EVET) as Evet,
       SUM(HAYIR) as Hayir,
       SUM(BOS) as Evet,
       SUM(GECERSIZ) as Gecersiz
FROM   sandiklar
WHERE  TUR = 'MM'

UNION

SELECT SUM(EVET),
       SUM(HAYIR),
       SUM(BOS),
       SUM(GECERSIZ)
FROM   sandiklar
WHERE  TUR = 'M'

UNION

SELECT SUM(EVET),
       SUM(HAYIR)r,
       SUM(BOS),
       SUM(GECERSIZ)
FROM   sandiklar
WHERE  TUR = 'MB'

输出结果为:

enter image description here

我的问题是; 我可以进行该查询,以便所有三行都是一行,包含12个列,并根据Where条件命名列。

mmEvet mmHayir mmBos mmgecersiz mEvet mHayir mBos mgecersiz mbEvet mbHayir mbBos mbgecersiz

这将是一排。

1 个答案:

答案 0 :(得分:1)

您可以使用SUM(CASE声明:

)来获取它
drop table if exists sandiklar;

create table if not exists sandiklar(tur text, EVET int, HAYIR int, BOS int, GECERSIZ int);

insert into sandiklar values
('MM', 100, 220, 310, 410),
('MM', 110, 230, 320, 420),
('MM', 120, 230, 360, 450),
('M',  110, 210, 370, 420),
('M',  140, 250, 320, 470),
('M',  120, 250, 330, 430),
('MB', 110, 260, 310, 490),
('MB', 150, 210, 310, 430),
('MB', 130, 210, 310, 430);

SELECT SUM(CASE WHEN TUR = 'MM' THEN EVET ELSE 0 END) as EvetMM,
       SUM(CASE WHEN TUR = 'MM' THEN HAYIR ELSE 0 END) as HayirMM,
       SUM(CASE WHEN TUR = 'MM' THEN BOS ELSE 0 END) as EvetMM,
       SUM(CASE WHEN TUR = 'MM' THEN GECERSIZ ELSE 0 END) as GecersizMM,
       SUM(CASE WHEN TUR = 'M' THEN EVET ELSE 0 END) as EvetM,
       SUM(CASE WHEN TUR = 'M' THEN HAYIR ELSE 0 END) as HayirM,
       SUM(CASE WHEN TUR = 'M' THEN BOS ELSE 0 END) as EvetM,
       SUM(CASE WHEN TUR = 'M' THEN GECERSIZ ELSE 0 END) as GecersizM,
       SUM(CASE WHEN TUR = 'MB' THEN EVET ELSE 0 END) as EvetMB,
       SUM(CASE WHEN TUR = 'MB' THEN HAYIR ELSE 0 END) as HayirMB,
       SUM(CASE WHEN TUR = 'MB' THEN BOS ELSE 0 END) as EvetMB,
       SUM(CASE WHEN TUR = 'MB' THEN GECERSIZ ELSE 0 END) as GecersizMB
FROM   sandiklar
WHERE  TUR IN ('MM','M','MB');

drop table if exists sandiklar;

| EvetMM | HayirMM | EvetMM | GecersizMM | EvetM  | HayirM  | EvetM  | GecersizM  | EvetMB | HayirMB | EvetMB | GecersizMB |
|-------:|--------:|--------|------------|--------|---------|--------|------------|--------|---------|--------|------------|
| 330    | 680     | 990    | 1280       | 370    | 710     | 1020   | 1320       | 390    | 680     | 930    | 1350       |

我在这里设置了一个示例:http://rextester.com/SIO50162