How can i calculate how many unique (hit_type = click) per campaign in the following scenario? :
CREATE TABLE statistics
(`id` int, `uid` int, `hit_type` varchar(10), `name` varchar(55), `date` date)
;
INSERT INTO statistics
(`id`, `uid`, `hit_type`, `name`, `date`)
VALUES
(1,'100','visit','campaign1','2015-03-18'),
(2,'100','visit','campaign1','2015-03-19'),
(3,'100','click','campaign1','2015-03-18'),
(4,'100','click','campaign1','2015-03-18'),
(5,'100','click','campaign1','2015-03-20'),
(6,'100','client','campaign1','2015-03-19'),
(7,'100','client','campaign1','2015-03-20'),
(8,'200','visit','campaign1','2015-03-19'),
(9,'200','visit','campaign1','2015-03-19'),
(10,'200','visit','campaign2','2015-03-20'),
(11,'200','click','campaign1','2015-03-18'),
(12,'200','click','campaign1','2015-03-19'),
(13,'200','client','campaign1','2015-03-19'),
(14,'200','client','campaign2','2015-03-20')
;
SELECT `name`,
SUM(IF(`hit_type` = 'click',1,0)) as click ,
SUM(IF(`hit_type` = 'visit',1,0)) as visit,
SUM(IF(`hit_type` = 'client',1,0)) as client
FROM `statistics`
WHERE `name` IN('campaign1','campaign2')
GROUP BY `name`
ORDER BY `name`
If you are looking for unique dates, then you can do:
SELECT `name`,
COUNT(DISTINCT CASE WHEN `hit_type` = 'click' THEN date END) as click ,
COUNT(DISTINCT CASE WHEN `hit_type` = 'visit' THEN date END) as visit,
COUNT(DISTINCT CASE WHEN `hit_type` = 'client' THEN date END) as client
FROM `statistics`
WHERE `name` IN('campaign1','campaign2')
GROUP BY `name`
ORDER BY `name`;
Related
I have two query to get count and sum of rate for unique ip's.
Query one groups by date and query two groups by country
This is the table
DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(5) UNSIGNED NOT NULL,
`country` int(3) UNSIGNED NOT NULL,
`user_ip` int(50) UNSIGNED NOT NULL,
`timestamp` int(10) UNSIGNED NOT NULL,
`rate` int(7) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `stats`
--
INSERT INTO `stats` (`id`, `user_id`, `country`, `user_ip`, `timestamp`, `rate`) VALUES
(1, 1, 1, 1111111111, 1489999983, 15000),
(2, 1, 2, 1111111112, 1489999984, 10000),
(3, 1, 1, 1111111111, 1489999985, 10000),
(4, 1, 1, 1111111111, 1490086333, 10000),
(5, 1, 2, 1111111111, 1490086334, 10000),
(6, 1, 1, 1111111121, 1490086335, 10000);
These are the queries I am using to get data
To get sum of rates based on date I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY DATE(FROM_UNIXTIME(`timestamp`))
Result
date count rate
20-03-2017 2 25000
21-03-2017 2 20000
To get sum of rates based on country I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`, `country`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`, `country`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY `country`
Result
country count rate
1 3 35000
2 1 10000
Since these two query are nearly same and fetches same rows from table is it possible to get both result from single query instead of two query.
Also please suggest if it can be be done in PHP effectively than MYSQL.
Thanks
Try this in php
$country="";
$groupByCondition="DATE(FROM_UNIXTIME(`timestamp`))";
if(/*BasedOnCountry*/){
$country=", `country`";
$groupByCondition = "`country`";
}
$query= "SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`"+ $country +"
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`"+ $country +"
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY "+ $groupByCondition ;
//execute the query and get the results
I need to get unique counts along with country counts and sum rate for every user
I have come up with this basic design for database where uid is user id
DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`uid` int(5) UNSIGNED NOT NULL,
`country` int(3) UNSIGNED NOT NULL,
`ip` int(10) UNSIGNED NOT NULL,
`date` int(10) UNSIGNED NOT NULL,
`timestamp` int(10) UNSIGNED NOT NULL,
`rate` int(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `stats`
(`id`, `uid`, `country`, `ip`, `date`, `timestamp`, `rate`) VALUES
(1, 1, 10, 1111111111, 2222222222, 3333333333, 100),
(2, 1, 10, 1111111112, 2222222222, 3333333333, 100),
(3, 2, 10, 1111111111, 2222222222, 3333333333, 100),
(4, 1, 10, 1111111114, 2222222223, 3333333333, 100),
(5, 1, 11, 1111111112, 2222222223, 3333333333, 100),
(6, 1, 10, 1111111111, 2222222223, 3333333333, 100);
And this is the query I am using to fetch daily counts
$query="
SELECT `uid`,
COUNT(DISTINCT `ip`)AS `count`,
`country`,
SUM(`rate`) AS `sum`,
`date`
FROM `stats`
GROUP BY `uid`, `date`
";
$result=mysqli_query($connection, $query) or trigger_error(mysqli_error($connection), E_USER_ERROR);
while($row = mysqli_fetch_assoc($result)){
echo 'userid:'.$row['uid'].' count:'.$row['count'].' country:'.$row['country'].' sum:'.$row['sum'].' date:'.$row['date'].'<br>';
};
I am getting this result
userid:1 count:2 country:10 sum:200 date:2222222222
userid:1 count:3 country:10 sum:300 date:2222222223
userid:2 count:1 country:10 sum:100 date:2222222222
Expected result
userid:1 count:2 country:10=>2 sum:200 date:2222222222
userid:1 count:3 country:10=>2, 11=>1 sum:300 date:2222222223
userid:2 count:1 country:10=>1 sum:100 date:2222222222
I guess I need something like SELECT DISTINCT country FROM stats to get country counts in main query.
Please see and suggest any possible way to do this.
Thanks
You can use subquery to achieve this:
SELECT
t.uid,
SUM(t.count) AS count,
GROUP_CONCAT(CONCAT(t.country, ' => ', t.views) SEPARATOR ', ') AS country,
SUM(t.sum) as sum,
t.date
FROM (
SELECT
s.uid,
COUNT(DISTINCT s.ip) AS count,
s.country,
COUNT(s.country) as views,
SUM(s.rate)AS sum,
s.date
FROM stats s
GROUP BY uid, date, country
) AS t
GROUP BY
t.uid,
t.date
Also available at sqlfiddle.
SUM needs a column and you gave string 'rate' in it, remove the ' from rate column name try this,
SELECT
COUNT(DISTINCT `ip`)AS `count`,
`country`,
SUM(rate) AS `sum`
FROM `stats`
GROUP BY `uid`, `date`
You will have to add country into the GROUP condition too:
SELECT
COUNT(DISTINCT `ip`) AS `count`,
`country`,
COUNT(`country`) as `countryViewsByUser`, -- added
SUM(`rate`)AS `sum`
FROM
`stats`
GROUP BY
`uid`,
`date`,
`country` -- added
You will just need to add country to your group by clause like below
$query="
SELECT
COUNT(DISTINCT `ip`)AS `count`,
`country`,
COUNT(DISTINCT `country`) AS country_count,
SUM(`rate`) AS `sum`
FROM `stats`
GROUP BY `country`, `uid`, `date`
";
And please you need to move away from mysqli_* functions, and take a look at PDO instead
Here is my Schema for tables :
CREATE TABLE users (`id` int, `name` varchar(50));
INSERT INTO users (`id`, `name`) VALUES (1, 'Test 1'), (2, 'Test 2'), (3, 'Test 3');
CREATE TABLE recipes (`id` int, `user_id` int , `name` varchar(100));
INSERT INTO recipes (`id`, `user_id`, `name`) VALUES
(null, 1, 'Receipe 1');
I need individual user receipe count, for that i've joined my user table with receipes, please look at below query
SELECT `User`.`id`, count('recipes.id') as recipes_cnt FROM `users` AS `User`
LEFT JOIN `recipes` AS `Recipe` ON (`User`.`id` = `Recipe`.`user_id`)
GROUP BY `User`.`id`
But it's giving count as 1 even if there are no receipes for user (normally it should be zero).
Here is mysql fiddle
Why am i getting results like this ?
please help me
Thanks in advance
I modified your SQL. replace count('recipes.id') to count(Recipe.id). These result gives ZERO's.
SELECT `User`.`id`, count(`Recipe`.id) as recipes_cnt FROM `users` AS `User`
LEFT JOIN `recipes` AS `Recipe` ON (`User`.`id` = `Recipe`.`user_id`)
GROUP BY `User`.`id`
Thank you.
There's a slight typo in your count:
count('recipes.id')
This is counting the string "recipes.id".
You need to count by the actual column:
count(Recipe.id)
I have the query below that uses union.
"SELECT * FROM (
SELECT 1 AS `table`,
`comment_post_id` AS `feed_id`,
`blog_id` AS `from_blog`,
`comment_author` AS `author`,
`comment_content_stripped` AS `feed_title`,
`comment_content` AS `post_content_s`,
`type` AS `type`,
null AS `object_type`,
`comment_date_gmt` AS `date`
FROM `wp_site_comments`
UNION
SELECT 2 AS `table`,
`post_id` AS `feed_id`,
null AS `from_blog`,
`blog_id` AS `author`,
`post_title` AS `feed_title`,
`post_content_stripped` AS `post_content_s`,
`post_type` AS `type`,
null AS `object_type`,
`post_published_gmt` AS `date`
FROM `wp_site_posts`
UNION
SELECT 3 AS `table`,
`object_id` AS `feed_id`,
`blog_id` AS `from_blog`,
`user_id` AS `author`,
null AS `feed_title`,
null AS `post_content_s`,
`type` AS `type`,
`object_type` AS `object_type`,
`date_added` AS `date`
FROM `wp_global_likes`
UNION
SELECT 4 AS `table`,
`object_id` AS `feed_id`,
null AS `from_blog`,
`user_id` AS `author`,
null AS `feed_title`,
null AS `post_content_s`,
`type` AS `type`,
`object_type` AS `object_type`,
`date_added` AS `date`
FROM `wp_global_followers`
) AS tb
ORDER BY `date` DESC"
Basically I wanted to select only the rows where author is in a comma separated values as follows:
eg. $blog_ids = (23, 55, 19, 10) and $user_ids = (22, 55, 19, 40)
The first table in union, the author is comment_author which is a user id.
The second table in union, the author isblog_id` which is a blog id.
The third and fourth table in union, the author is user_id which is a user_id.
Now, I wanted to somehow distinct the author as blog id and user id so my query will select rows where author is in $blog_ids and $user_ids uniquely.
I used,
WHERE author in (" . $blog_ids . ") and it returns correct. Now I wanted to include $user_id.
Please note that $blog_ids and $user_ids may have a same value.
I hope you get what I mean, this is i guess the best explanation I can make.
I have a table with the following info...
Id | orderNumber | orderDate | customerId
orderDate is a MySQL datetime field and the current day, month, year and time is inserted into the database at the time the record is written.
So my question is how would I pull a list of orders for a certain day of this current week. My goal is to use the google charts API to make a chart for "This Week's Sales" that says something like:
var data = google.visualization.arrayToDataTable([
['Day', 'Sales'],
['Mon', 1],
['Tue', 0],
['Wed', 4],
['Thurs', 3],
['Fri', 0],
]);
Let's do exactly what you want:
SELECT
WEEKDAY(`datetime_field`) AS `week_day`,
COUNT(*) AS `sale_count`
FROM `orders`
WHERE YEARWEEK(`datetime_field`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;
This returns a set of records with week_day and sale_count. Learn more here. Use NOW() if you use local datetime or use UTC_TIMESTAMP() if you play by GMT.
Do keep in mind I don't know your database name or the fields' names. You need to fill those in.
WORKING EXAMPLE:
CREATE TABLE `orders` (
`OrderID` int(11) NOT NULL AUTO_INCREMENT,
`OrderDate` datetime NOT NULL,
`OrderValue` decimal(7,2) unsigned NOT NULL,
PRIMARY KEY (`OrderID`)
);
INSERT INTO `orders` VALUES ('1', '2012-10-29 14:02:19', '100.00');
INSERT INTO `orders` VALUES ('2', '2012-10-30 14:02:19', '123.00');
INSERT INTO `orders` VALUES ('3', '2012-10-31 14:02:19', '103.00');
INSERT INTO `orders` VALUES ('4', '2012-11-01 14:02:19', '232.00');
INSERT INTO `orders` VALUES ('5', '2012-11-02 14:02:19', '321.00');
INSERT INTO `orders` VALUES ('6', '2012-11-03 14:02:19', '154.00');
INSERT INTO `orders` VALUES ('7', '2012-11-04 14:02:19', '112.00');
INSERT INTO `orders` VALUES ('8', '2012-10-29 14:02:19', '100.00');
SELECT
WEEKDAY(`OrderDate`) AS `week_day`,
COUNT(*) AS `sales_count`,
SUM(`OrderValue`) AS `sales_value`
FROM `orders`
WHERE YEARWEEK(`OrderDate`) = YEARWEEK(NOW())
GROUP BY `week_day`
ORDER BY `week_day` ASC;
This is SQL to create a table, add 1 order per day for this week but 2 on Monday. And the query to fetch the report.
AND HERE'S SQLFIDDLE.COM SAMPLE.