[英]count and sum different values per each day
how count different values per each day ? 如何计算每天不同的价值? and the total value for each day? 和每天的总价值? in one request. 在一个请求中。
key1 | key2 | tdate | tview
1 | 20161123454647 | 2016-11-23 11:11:11 | view1
2 | 20161123454648 | 2016-11-23 11:11:11 | view2
3 | 20161122454649 |2016-11-22 11:11:11 | view2
4 | 20161122454650 |2016-11-22 11:11:11 | view1
5 | 20161122454653 |2016-11-22 11:11:11 | view2
6 | 20161122454661 |2016-11-22 11:11:11 | view2
7 | 20161121454622 |2016-11-21 11:11:11 | view3
8 | 20161121454679 |2016-11-21 11:11:11 | view1
9 | 20161121454684 |2016-11-21 11:11:11 | view3
I found to count the total of all values of tview per day : 我发现每天计算tview的所有值的总和:
SELECT DATE(tdate) Date, COUNT(DISTINCT tview) totalOfViews FROM mytable GROUP BY DATE(tdate) SELECT DATE(tdate)Date,COUNT(DISTINCT tview)totalOfViews FROM mytable GROUP BY DATE(tdate)
I have a key (key2) which the concatenation of date and the number of a render because I don't want to hive two same render in the same day. 我有一个键(key2),它连接日期和渲染的数量,因为我不希望在同一天内同时渲染两个相同的渲染。
It's most easy for me when I insert a new render with 'INSERT ON DUPLICATE key2 UPDATE'. 当我插入一个带有'INSERT ON DUPLICATE key2 UPDATE'的新渲染时,对我来说最容易。 I update just the number of view with one request. 我只用一个请求更新视图的数量。 I don't know 'INSET ON DUPLICATE' <2 differents keys> UPDATE :newview. 我不知道'INSET ON DUPLICATE'<2个不同的键>更新:newview。 Interesting question too ;-) 有趣的问题;-)
The date is a timestamp in my table. 日期是我表格中的时间戳。
I use php 7, MySQL and PDO to do statement. 我使用php 7,MySQL和PDO来做声明。
One of interesting output: 一个有趣的输出:
day | totaView1 | totalView2 | totalView3 | totalView1+view2 |totalOfViews
2016-11-23 | 1 | 1 | 0 | 2 | 2
2016-11-22 | 1 | 3 | 0 | 4 | 4
2016-11-21 | 1 | 0 | 2 | 1 | 3
After i found to range date of request and compare évolution of number view per day. 在我找到请求的范围日期并比较每天的数字视图的évolution之后。 Example: 例:
Day (currentmonth) | totaView1 | totalView1 (lastmonth) |totalOfViews
Is the "alter table" can do this result? “alter table”可以做到这个结果吗?
One possibility is to use conditional aggregation: 一种可能性是使用条件聚合:
SELECT DATE(tdate) AS day,
SUM(CASE WHEN tview = 'view1' THEN 1 ELSE 0 END) AS totaView1,
SUM(CASE WHEN tview = 'view2' THEN 1 ELSE 0 END) AS totaView2,
SUM(CASE WHEN tview = 'view3' THEN 1 ELSE 0 END) AS totaView3,
SUM(CASE WHEN tview = 'view1' OR tview = 'view2'
THEN 1 ELSE 0 END) AS totaView1Or2,
COUNT(*) AS totalOfViews
FROM mytable
GROUP BY DATE(tdate)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.