我有表格并插入:
CREATE TABLE IF NOT EXISTS `klik_zona` (
`kode_zona` int(10) unsigned NOT NULL,
`klik` int(10) unsigned NOT NULL,
PRIMARY KEY (`kode_zona`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `klik_zona` (`kode_zona`, `klik`) VALUES
(1, 45);
CREATE TABLE IF NOT EXISTS `tampil_zona` (
`kode_zona` int(10) unsigned NOT NULL,
`tanggal` date NOT NULL,
`tampil` int(10) unsigned NOT NULL,
PRIMARY KEY (`kode_zona`,`tanggal`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tampil_zona` (`kode_zona`, `tanggal`, `tampil`) VALUES
(1, '2014-03-16', 100),
(1, '2014-03-17', 23);
CREATE TABLE IF NOT EXISTS `zona_iklan` (
`kode_zona` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`kode_zona`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `zona_iklan` (`kode_zona`) VALUES
(1),
(2),
(3);
我的查询如下:
SELECT z.kode_zona, SUM( tz.tampil ) , SUM( kz.klik )
FROM zona_iklan z
LEFT JOIN tampil_zona tz ON tz.kode_zona = z.kode_zona
LEFT JOIN klik_zona kz ON kz.kode_zona = z.kode_zona
GROUP BY z.kode_zona
但它给出了结果:
kode_zona SUM(tz.tampil) SUM(kz.klik)
1 123 90
2 NULL NULL
3 NULL NULL
我希望得到结果:
kode_zona SUM(tz.tampil) SUM(kz.klik)
1 123 45
2 NULL NULL
3 NULL NULL
请允许任何人帮助我。如何进行查询以便它显示出我希望得到的信息......
感谢。
答案 0 :(得分:0)
尝试此查询:
SELECT distinct z.kode_zona, SUM(distinct tz.tampil ) , SUM(distinct kz.klik )
FROM zona_iklan z
LEFT JOIN tampil_zona tz ON z.kode_zona = tz.kode_zona
LEFT JOIN klik_zona kz ON z.kode_zona = kz.kode_zona
GROUP BY z.kode_zona
我认为,这就是你想要的东西
答案 1 :(得分:0)
select kode_zona,
sum(case when splitter = 'tampil' then summer else 0 end) as sum_tampil,
sum(case when splitter = 'klik' then summer else 0 end) as sum_klik
from (SELECT 'tampil' as splitter, z.kode_zona, SUM(tz.tampil) as summer
FROM zona_iklan z
LEFT JOIN tampil_zona tz
ON tz.kode_zona = z.kode_zona
GROUP BY z.kode_zona
union all
SELECT 'klik' as splitter, z.kode_zona, SUM(kz.klik) as summer
FROM zona_iklan z
LEFT JOIN klik_zona kz
ON kz.kode_zona = z.kode_zona
GROUP BY z.kode_zona) x
group by kode_zona
SQL小提琴测试:http://sqlfiddle.com/#!2/a8f4f2/15/0
答案 2 :(得分:0)
另一个想法......
SELECT x.kode_zona
, y.type
, COALESCE(SUM(y.value),0) ttl
FROM zona_iklan x
LEFT
JOIN
( SELECT kode_zona, 'klik' type, klik value FROM klik_zona
UNION
SELECT kode_zona, 'tampil' , tampil value FROM tampil_zona
) y
ON y.kode_zona = x.kode_zona
GROUP
BY x.kode_zona
, y.type;