Tring to calculate count according to coloumn value with case statement and I used following code for doing this:
SET #tempVariable1 := 0;
SET #tempVariable2 := 0;
SELECT EMPLOYEEID,count(ADNUMBER),
CASE
WHEN AEERROR <> '--' then #tempVariable1:=#tempVariable1+1
ELSE 0
END AS Ext_err,
CASE
WHEN INTERNALERRORS <> '--' then #tempVariable2:=#tempVariable2+1
ELSE 0
END AS Int_err
FROM employee_productivity_details group by(EMPLOYEEID) LIMIT 2,20;
It works correct when I run on workbench but when I set this query in PHP variable like $sql then it shows error. So how can I set temperory variable with in query? Any other way to do this?
Does this do what you want?
SELECT EMPLOYEEID, count(ADNUMBER),
SUM(AEERROR <> '--') AS Ext_err,
SUM(INTERNALERRORS <> '--' ) AS Int_err
FROM employee_productivity_details
group by(EMPLOYEEID)
LIMIT 2, 20;
This is working fine for me as per need.
SELECT EMPLOYEEID,
count(ADNUMBER),
COALESCE(SUM(CASE INTERNALERRORS WHEN INTERNALERRORS <> '--'
THEN 0 ELSE 1 END), 0) as IntErr,
COALESCE(SUM(CASE AEERROR WHEN AEERROR <> '--'
THEN 0 ELSE 1 END), 0) AS ExtErr
FROM employee_productivity_details
group by(EMPLOYEEID) order by EMPLOYEEID LIMIT 2,20;
Related
I working on one complex listing from database and decide to do all possible requests via one query.
Here is working example:
"SELECT
`c`.`categories_id`,
`c`.`categories_status`,
IF(`c`.`categories_status` = 1, 'Active', 'Not Active') AS `categories_status_name`,
TRIM(`cd`.`categories_name`) AS `categories_name`,
TRIM(`cd`.`concert_date`) AS `concert_date`,
TRIM(`cd`.`concert_time`) AS `concert_time`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `p`.`products_quantity` > 0 THEN `p`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`p`.`products_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`products` `p`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`p`.`products_id` = `ptc`.`products_id`
)) AS `products_available`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`op`.`final_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`op`.`products_id` = `ptc`.`products_id`
AND
`op`.`orders_products_status` != 1
)) AS `products_sold`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`op`.`final_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`op`.`products_id` = `ptc`.`products_id`
AND
`op`.`orders_products_status` = 1
)) AS `products_pending`
FROM
`categories` `c`,
`categories_description` `cd`
WHERE
`c`.`categories_id` = `c`.`section_id`
AND
`cd`.`categories_id` = `c`.`categories_id`
GROUP BY `c`.`categories_id`
ORDER BY `c`.`categories_status` DESC;"
This work great but my main problem is how to do check IF/ELSE or CASE WHEN for custom defined new fields: products_available, products_sold and products_pending?
Problem is that if products not exists inside table orders_products I not get my generated JSON and that's made a small conflict inside PHP.
I can do check in PHP but want to avoid that part and just print JSON like:
{"total_quantity":0,"total_price":"0.0000"}
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
*
WHERE `products_id` =
(SELECT COALESCE(`products_id`,0))
*
AND
`ptc`.`section_id` = `cd`.`section_id`
So i have a Joomla site and in the joomla documentation I can't find anything to do with MySQL's IF, ELSE function within a query.
The part of the query i need a if statement in MySQL is here.
$query->where($db->quoteName('container').' != 1');
It should be doing something like this :
$query->where('IF '.$db->quoteName('server_number').' != '.$number.' THEN '$query->where($db->quoteName('container').' != 1');' END');
If the $number input does not match with the server_number column data then to add a where statement to the mysql query.
Full MySQL Query :
SELECT a.*,ext.media_type
FROM database_hwdms_processes AS a
LEFT JOIN database_hwdms_media AS media ON media.id = a.media_id
LEFT JOIN database_hwdms_ext AS ext ON ext.id = media.ext_id
WHERE (a.status = 1 || a.status = 3) AND a.attempts < 5 AND `container` != 1 AND
server = 1
ORDER BY a.media_id ASC
Want to add a "IF server_number != 1 THEN WHERE container != 1 END" would mean replacing "AND container != 1"
I figured out a better way to resolve my problem using MySQL's
OR ||
function
So my fixed code became this :
PHP :
$query->where('('.$db->quoteName('server_number').' = '.$number.' || '.$db->quoteName('container').' != 1 )');
In plain MySQL text :
SELECT a.*,ext.media_type
FROM database_hwdms_processes AS a
LEFT JOIN database_hwdms_media AS media ON media.id = a.media_id
LEFT JOIN database_hwdms_ext AS ext ON ext.id = media.ext_id
WHERE (a.status = 1 || a.status = 3) AND a.attempts < 5 AND ( `server_number` = 1 || `container` != 1 )AND
server = 1
ORDER BY a.media_id ASC
i am trying to output statistics of calls made by agents across all dialing campaigns called for the day. there are multiple campaigns, currently 3, dialed in a day. I get the campaign data from a table name that changes by campaign like so custom_16546546 and custom_1564654. I run a query to get the numeric part of the column name then pass that as a variable in to another query that outputs the users statistics. This is where it only displays data from what i can tell is the last query loops information. I have displayed the array data from the first query to confirm the table names are being stored and it looks fine.
$today = "2013-05-29";
$customquery = "SELECT distinct( entry_list_id) FROM vicidial_list where entry_list_id > 0 and last_local_call_time between '$today 00:00:00' and '$today 23:59:59';" ;
$customresult = mysql_query($customquery) or die(mysql_error());
$customrows = mysql_num_rows($customresult);
while ($customrowResult = mysql_fetch_array($customresult))
{
$customID[] = $customrowResult["entry_list_id"];
}
$z = 0;
if(!$customID){
//echo " Please Select a valid date range: ".$today. " - ".$today." is not valid" ;
}else{
while($z<$customrows)
{
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
vicidial_log.list_id,
COUNT(CASE WHEN (vicidial_log.status = 'SALE') THEN 1 ELSE null END) as sumcountSamnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].up_amt <> '') THEN 1 ELSE null END) as sumcountupAmnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].cc_num <> '') THEN 1 ELSE null END) as sumccverifiedcountAmnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].bank_act <> '') THEN 1 ELSE null END) as sumbankverifiedcountAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].cc_num <> '') THEN custom_$customID[$z].s_amount ELSE null END) as sumccverifiedAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].bank_act <> '') THEN custom_$customID[$z].s_amount ELSE null END) as sumbankverifiedAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].d_amt ELSE null END) as sumDamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].up_amt ELSE null END) as sumUpamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].md_amt ELSE null END) as sumMdamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].s_amount ELSE null END) as sumSamnt
FROM
vicidial_log
INNER JOIN
vicidial_users
ON
(vicidial_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$z]
ON
(vicidial_log.lead_id = custom_$customID[$z].lead_id)
WHERE
call_date
BETWEEN
'$today 00:00:00'
AND
'$today 23:59:59'
AND
vicidial_log.user != 'VDAD'
AND
vicidial_users.user_group != 'TX-Training'
GROUP BY
vicidial_log.user, vicidial_log.campaign_id
";
//This query is used to sum loop data data
$queryResult = mysql_query($query) or die(mysql_error()); //This line perfomrs query error handling
$z++;
}
here is a snippet of how the data is displayed
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>\n";
//--fullname and userID
echo "<td> ".$row["full_name"]. " - ".$row["user"]."</td>\n";
//Agent total sales amount
if ($row["sumcountSamnt"] == '0') {
echo "<td>$nosalestxt</td>\n";
} else {
echo "<td> $".$row["sumSamnt"]."</td>\n";
}
}
So i want to be able to display a sum total of data for each user from all the campaigns they dialed from.
Thanks in advance for your help
EDIT: i use &row from a while loop to output the data and yes Chris i would like to store it an array, but i guess im just missing it, thanks again
Based on the code snippets you have given it looks like you are overwriting the value of $queryResult after each execution of the loop. Perhaps you meant to execute the query and put the results into an array (or something similar) to loop over and display later.
Also I notice you reference $row[] in your output, how are you assigning a value to that variable?
Let's say your running a query and you have a lot of different user inputs that may not find an exact match. Now would it be possible to do something like the following?
$query = "SELECT *,
CASE matchingValues
WHEN $field1 LIKE '$a' THEN value = '1' ELSE value = '0'
WHEN $field2 LIKE '$b' THEN value = '1' ELSE value = '0'
WHEN $field3 LIKE '$c' THEN value = '1' ELSE value = '0'
WHEN $field4 LIKE '$d' THEN value = '1' ELSE value = '0'
WHEN $field5 LIKE '$e' THEN value = '1' ELSE value = '0'
END AS score
FROM . $usertable
WHERE
$field1 LIKE '$a' AND
$field2 LIKE '$b' AND
$field3 LIKE '$c' AND
$field4 LIKE '$d' AND
$field5 LIKE '$d'
ORDER BY score DESC";
if($result = mysql_query($query)) {
if(mysql_num-rows($result)==NULL) {
echo 'No Results Found';
}else{
....
Yes this is possible, though you would do it without the WHERE clause, and you would want to add up all the inputs instead of using a CASE to get the total score. Since each LIKE statement returns a boolean 1 or 0, you can just add them up to find out how many matches you have. A HAVING clause then limits to rows returned with a score > 0, if you want to return only those that actually matched.
SELECT *,
(($field1 LIKE '$a') +
($field2 LIKE '$b') +
($field3 LIKE '$c') +
($field4 LIKE '$d') +
($field5 LIKE '$e')) AS score
FROM . $usertable
HAVING score > 0
ORDER BY score DESC";
We assume you have already added % wildcards to the LIKE variables, and that they have been properly escaped prior to use in your query.
However, while you can do it this way (a poor-man's full-text search), MySQL offers the possibility of creating a full text index across multiple columns on MyISAM tables.
Update: To artificially weight them...
If you have a need to weight them, use CASE statements and put in higher numbers for the top few:
SELECT *,
(CASE WHEN ($field1 LIKE '$a') THEN 5 ELSE 0 END +
CASE WHEN ($field2 LIKE '$b') THEN 4 ELSE 0 END +
CASE WHEN ($field3 LIKE '$c') THEN 3 ELSE 0 END +
CASE WHEN ($field4 LIKE '$d') THEN 2 ELSE 0 END +
CASE WHEN ($field5 LIKE '$e') THEN 1 ELSE 0 END) AS score
FROM . $usertable
HAVING score > 0
ORDER BY score DESC";
To just enforce that the first one match, put it in your WHERE clause.
SELECT *,
(($field1 LIKE '$a') +
($field2 LIKE '$b') +
($field3 LIKE '$c') +
($field4 LIKE '$d') +
($field5 LIKE '$e')) AS score
FROM . $usertable
WHERE $field1 LIKE '$a'
HAVING score > 0
ORDER BY score DESC";
Again, to be clear - a very closely related functionality is already built-in and optimized in MySQL's full text indexing and the MATCH keyword.
I'm trying to show only every 2nd row after selecting something from my DB.
My select looks like this:
SELECT * FROM table where partnerID = '1'
Now from the results of that select query I want to get only every 2nd row.
Is that possible ?
$count = 0;
while($row = mysql_fetch_array($results)) {
$count++;
if($count % 2 == 1) continue;
// What you want to do with the rows you don't want to skip here...
}
On a side note, you can use this same strategy to only show every 3rd row, or every 4th row, simply by changing what number you put next to the modulus operator
if($count % 3 != 0) continue; // Show only every third row
if($count % 4 != 0) continue; // Show only every fourth row
SELECT * FROM (
SELECT #n := #n + 1 AS position,
t.*
FROM (SELECT #n:=0) counter,
table t
WHERE partnerID = 1)
AS query
WHERE MOD(position,2) = 0
You can do this in the following way:
SELECT * FROM
(
SELECT
#I := #I + 1 AS rowNumber,
tablename.*
FROM
tablename,
(SELECT #I := 0) VT1
WHERE partnerID = 2
ORDER BY ID
) NumberedRows
WHERE MOD(rowNumber, 2)=0
;
Not sure if this is the right answer, but it looks like you would need to use something like MOD function (http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_mod)
SELECT * FROM `table` WHERE id & 1;
Would return odd rows