how to convert count(*) and group by queries to yii and fetch data from it - select

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?

Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.

Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/

If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();

Related

getting the 1st row in a database

I want to get the 1st row of the result depends on which build the room is. For example Building 1 have 1-200 rooms and Building 2 have 201-400 rooms. The code I tried is below. I have used the MIN in the where clause but I got all the rooms instead of having one.
$query = $this->db->query("SELECT * FROM `ha_utility_reading`");
if ($query->num_rows == 0) {
echo "some data match";
$lastroom = $this->db->select("*")->from("rooms")
->where("(SELECT MIN(room_num) FROM ha_rooms) and bldg_num = '$bldg_num'")
->get()->result_array();
foreach($lastroom as $key => $test) {
$output['room_num'][] = $test['room_num'];
json_encode($output);
}
You get all the rows because you need a group by clause. Anyway, the best way to do this is just adding this to your query:
order by room_num asc limit 1;
Try this,
select * from rooms order by room_num asc limit 1;

Column is not updating in postgresql

I tried to update my table like below:
$query = "select *
FROM sites s, companies c, tests t
WHERE t.test_siteid = s.site_id
AND c.company_id = s.site_companyid
AND t.test_typeid = '20' AND s.site_id = '1337'";
$queryrow = $db->query($query);
$results = $queryrow->as_array();
foreach($results as $key=>$val){
$update = "update tests set test_typeid = ? , test_testtype = ? where test_siteid = ?";
$queryrow = $db->query($update,array('10','Meter Calibration Semi Annual',$val->site_id));
}
The above code is working good. But in update query , The column test_typeid is not updated with '10'. Column test_typeid is updating with empty value. Other columns are updating good. I dont know why this column test_typeid is not updating? And the column test_typeid type is integer only. I am using postgreSql
And My table definition is:
What i did wrong with the code. Kindly advice me on this.
Thanks in advance.
First, learn to use proper JOIN syntax. Never use commas in the FROM clause; always use proper explicit JOIN syntax.
You can write the query in one statement:
update tests t
set test_typeid = '10',
test_testtype = 'Meter Calibration Semi Annual'
from sites s join
companies c
on c.company_id = s.site_companyid
where t.test_siteid = s.site_id and
t.test_typeid = 20 and s.site_id = 1337;
I assume the ids are numbers, so there is no need to use single quotes for the comparisons.

How to do a select statement query with comma separator?

I need to do a simple query, Select Statement
I want to search in Table all record with value "ValueA, ValueB".
If I use this code, not work well:
String255 valueToFilter;
valueToFilter = 'ValueA, ValueB';
select count (RecId) from MyTable
where MyTable.Field like valueToFilter ;
But not working, I need to keep all record with value "ValueA" or "ValueB", if in the file there is value like : "ValueA, ValueC" I want to get too.
I don't know the number of values (valueToFilter).
Thanks!
From my point of view the easiest way to accomplish this is to split your filter string:
String255 valueToFilterA = 'ValueA';
String255 valueToFilterB = 'ValueB';
;
select count (RecId) from MyTable
where MyTable.Field like valueToFilterA
|| MyTable.Field like valueToFilterB;
If you don't know the number of values you should use query object to add ranges dynamically:
Query query = new Query();
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange queryRange;
container conValues;
;
qbds = query.addDataSource(tableNum(MyTable));
for (i = 1; i <= conlen(conValues); i++)
{
queryRange = qbds.addRange(fieldNum(MyTable, Field));
queryRange.value(SysQuery::valueLike(conPeek(conValues, i)));
}
queryRun = new QueryRun(query);
info(strFmt("Records count %1", SysQuery::countTotal(queryRun)));

mysqli - fetch several rows applying several where conditions

With only one query I want to fetch specific rows that contains a range of several string values. Is it possible to modify my WHERE to do this?
This is the code for one country but I want to select several rows for several countries. For example: Jamaica, Portugal and Dominica.
// Select countries to show
$specific_country = Dominica;
// Select and write SPECIFIC ROWS data
$result = mysqli_query($con, "SELECT * FROM $table WHERE Country='$specific_country'");
This will only get the rows of Dominica but I wanted to use something similar to get Jamaica, Portugal and Dominica but all on the same query.
You can use IN()
SELECT *
FROM table_name
WHERE Country IN('Jamaica', 'Portugal', 'Dominica')
Here is SQLFiddle demo
In php
$countries = array('Jamaica', 'Portugal', 'Dominica');
$sql = "SELECT * FROM table_name WHERE Country IN('". implode("','", $countries) . "')";
$result = mysqli_query($con, $sql);
...

crytal report count total records

Im using query in crystal report like:
if({?User Name}) <>"ALL"
then
{COMN_USER_RESP_LINK_T.APPL_USER_NAME}={?User Name}
else
{COMN_USER_RESP_LINK_T.APPL_USER_NAME} ={COMN_USER_RESP_LINK_T.APPL_USER_NAME}
and
{COMN_USER_RESP_LINK_T.ENABLED}="Y"
this is actual query in sql:
SELECT
C.APPL_USER_NAME,
A.RESP_NAME,
B.MENU_NAME,
B.DESCRIPTION,
B.MODULE_NAME,
C.APPL_RESP
FROM COMN_RESPONSIBILITY_T A,
COMN_RESP_MENU_LINK_T B,
COMN_USER_RESP_LINK_T C
WHERE A.COMP_CODE = B.COMP_CODE
AND B.COMP_CODE = C.COMP_CODE
AND C.COMP_CODE = A.COMP_CODE
AND A.RESP_NAME = B.RESP
AND C.APPL_RESP = A.RESP_NAME
AND B.ENABLED = 'Y'
AND C.APPL_USER_NAME = c.APPL_USER_NAME
CASE #ACCT_CODE_FROM
WHEN 'ALL' THEN C.APPL_USER_NAME
ELSE #ACCT_CODE_FROM
END
ORDER BY APPL_USER_NAME,
RESP_NAME
I should select user name in parameter field(?user name), if I select ALL then I have to show all records ({COMN_USER_RESP_LINK_T.APPL_USER_NAME})
is the above query correct?
I would probably rephrase that as something like:
SELECT C.APPL_USER_NAME, A.RESP_NAME, B.MENU_NAME, B.DESCRIPTION,
B.MODULE_NAME, C.APPL_RESP
FROM COMN_RESPONSIBILITY_T A
INNER JOIN COMN_RESP_MENU_LINK_T B ON A.COMP_CODE = B.COMP_CODE
AND A.RESP_NAME = B.RESP
INNER JOIN COMN_USER_RESP_LINK_T C ON B.COMP_CODE = C.COMP_CODE
AND C.APPL_RESP = A.RESP_NAME
WHERE ((#ACCT_CODE_FROM = 'ALL') AND (B.ENABLED = 'Y'))
OR (C.APPL_USER_NAME = #ACCT_CODE_FROM)
ORDER BY APPL_USER_NAME, RESP_NAME
This gets you the details for either:
when ALL is selected, all accounts that are enabled; or
just the user code entered
i don't read your code because it is very dirty! but i think you can use SelectionFormula in crystal report. Certainly you can set it in code :
crystalReportViewer1.SelectionFormula ="(({?User Name}= 'ALL') AND ({B.ENABLED} = 'Y'))
OR ({C.APPL_USER_NAME} = #ACCT_CODE_FROM)"