кодесурса
«MYSQL

Функция MySQL COUNT (DISTINCT)

script1adsense2code
script1adsense3code

Функция COUNT (DISTINCT)

Функция MySQL COUNT (DISTINCT) возвращает количество строк с различными значениями, отличными от NULL.

Синтаксис:

 COUNT (DISTINCT expr, [expr ...])

Где expr - это заданное выражение.

Версия MySQL: 5.6

Пример: функция MySQL COUNT (DISTINCT)

Следующий оператор MySQL будет считать уникальный pub_lang и среднее значение no_page до 2 десятичных знаков для каждой группы cate_id.

Пример таблицы: book_mast


Код:

SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
FROM book_mast
GROUP BY cate_id;

Пример вывода:

 mysql> SELECT cate_id, COUNT (DISTINCT (pub_lang)), ROUND (AVG (no_page), 2)
    -> ОТ book_mast
    -> GROUP BY cate_id;
+ --------- + --------------------------- + ----------- ------------ +
| cate_id | COUNT (DISTINCT (pub_lang)) | КРУГЛЫЙ (AVG (no_page), 2) |
+ --------- + --------------------------- + ----------- ------------ +
| CA001 | 2 | 264,33 | 
| CA002 | 1 | 433,33 | 
| CA003 | 2 | 256,67 | 
| CA004 | 3 | 246,67 | 
| CA005 | 3 | 245,75 | 
+ --------- + --------------------------- + ----------- ------------ +
5 рядов в наборе (0,00 сек)

PHP скрипт

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>example-count-with-distinct- php mysql examples | w3resource</title>
<meta name="description" content="example-count-with-distinct- php mysql examples | w3resource">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Counting the unique language of publishing and average number of pages up to two decimal places within each group of category id:</h2>
<table class='table table-bordered'>
<tr>
<th>Category id</th><th>Unique language of publishing</th><th>Average number of pages up to two decimal places</th>
</tr>
<?php
$hostname="your_hostname";
$username="your_username";
$password="your_password";
$db = "your_dbname";
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT cate_id,COUNT(DISTINCT(pub_lang)),
ROUND(AVG(no_page),2)
FROM book_mast GROUP BY cate_id') as $row) {
echo "<tr>";
echo "<td>" . $row['cate_id'] . "</td>";
echo "<td>" . $row['COUNT(DISTINCT(pub_lang))'] . "</td>";
echo "<td>" . $row['ROUND(AVG(no_page),2)'] . "</td>";
echo "</tr>";
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

Посмотреть пример в браузере

JSP скрипт

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example-count-with-distinct</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String Host ="jdbc:mysql://localhost:3306/w3resour_bookinfo";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
connection = DriverManager.getConnection(Host, "root", "datasoft123");
statement = connection.createStatement();
String Data ="SELECT cate_id,COUNT(DISTINCT(pub_lang)),ROUND(AVG(no_page),2)FROM book_mast GROUP BY cate_id";
rs = statement.executeQuery(Data);
%>
<TABLE border="1">
<tr  width="10" bgcolor="#9979">
<td>Category id</td>
<td>Unique language of publishing</td>
<td>Average number of pages up to two decimal places</td>
</tr>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString("cate_id")%></TD>
<TD><%=rs.getString("COUNT(DISTINCT(pub_lang))")%></TD>
<TD><%=rs.getString("ROUND(AVG(no_page),2)")%></TD>
</TR>
<%   }    %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println("Can’t connect to database.");
}
%>
</body>
</html>

Предыдущая: COUNT () с группой по
Далее: GROUP_CONCAT ()

Новый контент: Composer: менеджер зависимостей для PHP , R программирования


script1adsense4code
script1adsense5code
disqus2code
script1adsense6code
script1adsense7code
script1adsense8code
buysellads2code