An explanation on COUNT() - sql

I have been trying to get the grasps of SQL, recently, and I was wondering if you could explain how you could use a WHERE/AND OR in a COUNT() to return the number of rows with a certain criteria...
Or am I looking into the wrong function? Any helpful comments are welcome
EDIT: Heres what I'm working with, I have a simple SELECT WHERE query to print out a profileName and profileIcon. I am using this as a test to see if COUNT works for what I want... I then want to run a COUNT to see how many ROWs are within the criteria.
$query = $con->query("SELECT * FROM user_settings WHERE Username='" . $_SESSION['user'] . "'");
while($row = $query->fetch_array()) {
echo '<tr><th>Current Icon:</th><td><img src="' . $row['ProfileIcon'] . '" /></td></tr>';
echo '<tr><th>Current Name:</th><td>' . $row['ProfileName'] . '</td></tr>';
}
$query = $con->query("SELECT SUM(CASE WHEN Username='" . $_SESSION['user'] ."' THEN 1 ELSE 0 END) FROM user_settings");
var_dump($query);
The var_dump produces: object(mysqli_result)#3 (0) { }

For a "conditional" COUNT, you can use a CASE expression and SUM, e.g.
SUM(CASE WHEN ColumnA = 'Bob' THEN 1 ELSE 0 END)
will count the number of rows where ColumnA is Bob, but will include all rows (whether they have Bob or not) in the result set.

I'd recommend that you read through the documentation for COUNT. It includes examples with fairly detailed explainations.
An example:
SELECT COUNT(*) FROM pet;
this would count all rows found in the pet table. You can append a WHERE-statement after this to include a certain criteria.

Something like this:
select x, count(*)
from y
where x = ?
group by x
having count(*) > ?
order by x
The having clause is optional.

Related

Case When formula to COUNT on results tab

On results tab of saved search, I would like to display a COUNT of Opportunities that do not have SLX in Title, Memo or Item Name. I'm using a transaction saved search.
I have tried a formula(numeric)results column and it returns incorrect results of one per grouped rep:
Formula(Numeric) Summary type: COUNT
CASE WHEN({title} = 'SLX') Or ({memo} = 'SLX') Or ({item.name} = 'SLX') THEN 1 ELSE 0 END
Counts one per Rep (grouped).
Hmmm . . . I think sum() is more appropriate:
SUM(CASE WHEN({title} = 'SLX') Or ({memo} = 'SLX') Or ({item.name} = 'SLX') THEN 1 ELSE 0 END)
Your expression is equivalent to COUNT(*), because COUNT() counts non-NULL values and all the values are either 1 or 0.

Mysql check limit 3 already in db

I wanna to make limit check. Primary - check if name already in last 3 lines. How to make?
$connect = db_connect();
$query = "SELECT * FROM `lastest` WHERE `name` LIKE '" .$name. "'";
$result = db_query($query, $connect);
if ($result) {
die('Already in db.'); }
Check is_exists column, this what i can suggest to you:
is_exists = 1 => Name exists
is_exists = 0 => Name doesn't exists
SELECT count(*) as is_exists,GROUP_CONCAT(`fname`) as a
FROM test.users
HAVING a LIKE "% YOUR_NAME %"
ORDER BY `fname` DESC
LIMIT 3 ;
Try it and let me know if it was help you
Don't hesitate ask any questions
Good luck
If your column id is "id" :
Googling "sql get last rows" (without quotes) leads to this page :
http://www.w3schools.com/sql/sql_func_last.asp
Pick up your db, and customize the request to get the 3 last lines. Then write a request querying a sub-request (this one who gets the 3 last lines) with your where statment...
So, assuming that your primary key is "id" :
SELECT COUNT(*)
FROM
(SELECT id, name
FROM lastest
ORDER BY id DESC
LIMIT 3) sub_lastest
WHERE `name` LIKE [name];

need to envelop query to count results

i have this query:
SELECT
[QUERY1].[py],
[QUERY1].[al],
[QUERY1].[ga],
[QUERY1].[sy],
[QUERY1].[pl]
FROM [tab-Sample] as QUERY1, [tab-Sample]
WHERE [tab-Sample].[py] = [QUERY1].[py] AND
[tab-Sample].[al] <> [QUERY1].[al]
I would like to write a query that jsut counts the results of this one, i cannot find where to insert the Count(*) also tried with Over() but im unable to manage this.
Wrap everything as a sub selection in the FROM. Make sure you name it however (Total).
COUNT (*) AS Amount FROM
(
SELECT
[QUERY1].[py],
[QUERY1].[al],
[QUERY1].[ga],
[QUERY1].[sy],
[QUERY1].[pl]
FROM [tab-Sample] as QUERY1, [tab-Sample]
WHERE [tab-Sample].[py] = [QUERY1].[py] AND
[tab-Sample].[al] <> [QUERY1].[al]
) Total

Codeigniter SQL Join with multiple ON clauses?

This is the SQL query displayed by codeigniter:
SELECT * FROM (status_updates) JOIN friend_connections ON ((
status_updates.userid=friend_connections.userid) OR
(status_updates.userid=friend_connections.friend_id)) WHERE
status_updates.enabled = "1" AND friend_connections.enabled = "1"
ORDER BY status_updates.date desc, status_updates.time desc LIMIT 20
The Codeigniter commands i used were:
$this->db->from('status_updates');
$this->db->order_by("status_updates.date", "desc");
$this->db->order_by("status_updates.time", "desc");
$this->db->limit(20);
$this->db->join('status_updates', '((status_updates.userid=friend_connections.userid) OR (status_updates.userid=friend_connections.friend_id))');
What i'm trying to do is select everything in two tables, status_updates and friend_connections. status_updates has the one column userid which i want to match with either userid or friend_id from friend_connections. Can someone tell me how i can do this please?
Also i noticed that codeigniter removes the two opening parentheses after the ON command in the above sql query.
Copy of your own answer in order to remove this from the unanswered stack:
$sql = "SELECT * FROM (status_updates) JOIN friend_connections ON ((status_updates.userid=friend_connections.userid) OR (status_updates.userid=friend_connections.friend_id)) WHERE status_updates.enabled = "1" AND friend_connections.enabled = "1" ORDER BY status_updates.date desc, status_updates.time desc LIMIT 20";
$status = $this->db->query($sql);
Please don't upvote. It's not my answer.

getting count(*) using createSQLQuery in hibernate?

I have several sql queries that I simply want to fire at the database.
I am using hibernate throughout the whole application, so i would prefer to use hibernate to call this sql queries.
In the example below i want to get count + name, but cant figure out how to get that info when i use createSQLQuery().
I have seen workarounds where people only need to get out a single "count()" from the result, but in this case I am using count() + a column as ouput
SELECT count(*), a.name as count FROM user a
WHERE a.user_id IN (SELECT b.user_id FROM user b)
GROUP BY a.name
HAVING COUNT(*) BETWEEN 2 AND 5;
fyi, the above query would deliver a result like this if i call it directly on the database:
1, John
2, Donald
1, Ralph
...
Alternatively, you can use
SQLQuery query = session.createSQLQuery("SELECT count(*) as num, a.name as name FROM user a WHERE a.user_id IN (SELECT b.user_id FROM user b) GROUP BY a.name HAVING COUNT(*) BETWEEN 2 AND 5;";
query.addScalar("num", Hibernate.INTEGER).addScalar("name", Hibernate.STRING);
// you might need to use org.hibernate.type.StandardBasicTypes.INTEGER / STRING
// for Hibernate v3.6+,
// see https://hibernate.onjira.com/browse/HHH-5138
List<Object> result = query.list();
// result.get(2*i + 0) -> i-th row num
// result.get(2*i + 1) -> i-th row name
I'm using this in case of time-pressure, imo much faster to code then creating your own beans & transformers.
Cheers!
Jakub
cheers for the info Thomas, worked wonderful for generating objects
the problem i had with my initial query was that "count" was a reserved word :P
when i changed the name to something else it worked.
If your SQL statement looks like this SELECT count(*) as count, a.name as name... you could use setResultTransformer(new AliasToBeanResultTransformer(YourSimpleBean.class)) on your Query.
Where YourSimpleBean has the fields Integer count and String name respectively the setters setCount and setName.
On execution of the query with query.list() hibernate will return a List of YourSimpleBeans.