MySQL:两个标准上多列中的整数值的计数和总和

时间:2015-10-30 13:18:48

标签: mysql sql count addition

我需要做同样的事情here。这次我希望得到一个基于两个标准的结果。所以我有一张这样的桌子。

0

我需要编写一个查询来计算每列中不等于publisherId的行,并且还会给出列中数字的实际总和,并根据{{1来排列结果}}。所以结果会是这样的。

Columns     |     Counts(91)   |    Sum(91)  |    Counts(12)   |    Sum(12)
----------------------------------------------------------------------------
images      |     1            |    4        |     2           |    13
videos      |     2            |    7        |     3           |    3
reviews     |     1            |    1        |     3           |    20

answer到我的其他问题的一个publisherId结果的查询是这样的。

SELECT 'images' as `columns`, SUM(images <> 0) as counts, SUM(images) as `sum`
FROM dpsreport where publisherId = 91
UNION ALL
SELECT 'videos', SUM(videos <> 0), SUM(videos)
FROM dpsreport where publisherId = 91
UNION ALL
SELECT 'reviews', SUM(reviews <> 0), SUM(reviews)
FROM dpsreport where publisherId = 91;

我如何实现这一结果?

3 个答案:

答案 0 :(得分:1)

这根本不需要join。这只是更有条件的聚合。我将展示发布者91的逻辑。您可以自己为12添加两列:

SELECT 'images' as `columns`,
       SUM(images <> 0 and publisherid = 91) as counts_91,
       SUM(case when publisherid = 91 then images else 0 end) as sum_91
FROM dpsreport
UNION ALL
SELECT 'videos',
       SUM(videos <> 0 and publisherid = 91) as counts_91,
       SUM(case when publisherid = 91 then videos else 0 end) as sum_91
FROM dpsreport
UNION ALL
SELECT 'reviews',
       SUM(reviews <> 0 and publisherid = 91) as counts_91,
       SUM(case when publisherid = 91 then reviews else 0 end) as sum_91
FROM dpsreport;

当你练习逻辑时,你应该更容易弄清楚如何自己解决这些问题。

答案 1 :(得分:1)

SELECT 'images' as `columns`, 
       IF(publisherId=91, SUM(images <> 0), 0) as counts91, 
       IF(publisherId=91, SUM(images), 0) as `sum91`, 
       IF(publisherId=12, SUM(images <> 0), 0) as counts12, 
       IF(publisherId=12, SUM(images), 0) as `sum12`
FROM dpsreport
group by publisherId 
UNION ALL
SELECT 'videos' as `columns`, 
       IF(publisherId=91, SUM(videos<> 0), 0) as counts91, 
       IF(publisherId=91, SUM(videos), 0) as `sum91`, 
       IF(publisherId=12, SUM(videos<> 0), 0) as counts12, 
       IF(publisherId=12, SUM(videos), 0) as `sum12`
FROM dpsreport
group by publisherId 
UNION ALL
SELECT 'reviews' as `columns`, 
       IF(publisherId=91, SUM(reviews<> 0), 0) as counts91, 
       IF(publisherId=91, SUM(reviews), 0) as `sum91`, 
       IF(publisherId=12, SUM(reviews<> 0), 0) as counts12, 
       IF(publisherId=12, SUM(reviews), 0) as `sum12`
FROM dpsreport
group by publisherId 

答案 2 :(得分:1)

如果您希望它能够处理任意数量的发布者,那么我建议您不必无限地增加列数,而是为发布商ID添加额外的列,并在不同的级别上处理重新组织:

SELECT publisherId, 'images' as `columns`, SUM(images <> 0) as counts, SUM(images) as `sum`
FROM dpsreport  GROUP BY publisherId
UNION ALL
SELECT publisherId, 'videos', SUM(videos <> 0), SUM(videos)
FROM dpsreport GROUP BY publisherId
UNION ALL
SELECT publisherId, 'reviews', SUM(reviews <> 0), SUM(reviews)
FROM dpsreport GROUP BY publisherId;