我的表格结构如下:
id |sourceid |item |freq |siteid |customerid
61 |226 |2 |1 |262 |1
301 |226 |1 |1 |262 |1
495 |1 |32 |1 |262 |1
658 |166 |8 |16 |262 |1
1 |2 |4 |1 |333 |2
我正在尝试根据“ freq”的值将“ item”的总和加在一起,并按“ customerid”和“ siteid”分组
因此,在上面的网站1中,客户1的站点262的总频率为35(2 + 1 + 32) 我需要对其他频率执行相同操作 我有下面的
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `new_view` AS
SELECT
`siteitems`.`customerID` AS `CID`,
`siteitems`.`siteID` AS `AID`,
SUM(`siteitems`.`item`) AS `Semi-annual`
FROM
`contractitems` `siteitems`
WHERE
(`siteitems`.`freq` = 1)
GROUP BY `siteitems`.`customerID` , `siteitems`.`siteID`
哪一位给我1的频率 我不确定如何在同一表格中添加频率为2等的另一列。
我应该删除WHERE子句并更改SUM(以某种方式)以仅对正确的频率求和,还是我需要再次加入表?
答案 0 :(得分:0)
根据您的描述,这应该可以满足您的要求:
select customerid, siteid, freq, sum(item)
from contractitems ci
group by customerid, siteid, freq
order by customerid, siteid, freq;
但是,您可能还需要条件聚合:
select customerid, siteid,
sum(case when freq = 1 then item else 0 end) as item_1,
sum(case when freq = 2 then item else 0 end) as item_2,
sum(case when freq = 4 then item else 0 end) as item_4,
sum(case when freq = 8 then item else 0 end) as item_8,
sum(case when freq = 16 then item else 0 end) as item_16
from contractitems ci
group by customerid, siteid
order by customerid, siteid;