select
(case when a.attr_type = 1 then a.value_int end) y,
(case when a.attr_type = 2 then a.value_int end) m,
(case when a.attr_type = 3 then a.value_int end) d,
sum(case when a.attr_type = 0 and a.value_int = 0 then i.count end) hosts_count,
sum(case when a.attr_type = 0 and a.value_int = 1 then i.count end) leads_count,
sum(case when a.attr_type = 0 and a.value_int = 1 then i.amount end) leads_amount
from stat_item i
inner join stat_item_attrs a on
a.item_id = i.id and (
(a.attr_type = 0 and a.value_int in (0,1))
or
a.attr_type in (1, 2,3)
)
group by y,m,d
select
y.value_int, m.value_int, d.value_int,
sum(case when k.value_int = 0 then i.count end) hosts_count,
sum(case when k.value_int = 1 then i.count end) leads_count,
sum(case when k.value_int = 1 then i.amount end) leads_amount
from stat_item i
inner join stat_item_attrs y on y.item_id = i.id and y.attr_type = 1/*y*/
inner join stat_item_attrs m on m.item_id = i.id and m.attr_type = 2/*m*/
inner join stat_item_attrs d on d.item_id = i.id and d.attr_type = 3/*d*/
inner join stat_item_attrs k on (k.item_id = i.id and k.attr_type = 0/*kind*/ and k.value_int in (0,1))
group by y.value_int, m.value_int, d.value_int
order by y.value_int desc, m.value_int desc, d.value_int desc
inner join stat_item_attrs y on y.item_id = i.id and y.attr_type = 1/*y*/
inner join stat_item_attrs m on m.item_id = i.id and m.attr_type = 2/*m*/
inner join stat_item_attrs d on d.item_id = i.id and d.attr_type = 3/*d*/
$config['base_url'] = sprintf('http://%s/', $_SERVER['HTTP_HOST']);