how to get row count in a table of different types in one table within same query - mysql

For Example,the table contains the column jobtype, the thing is we need to count no. of rows of same jobtype and at the same time for all the jobs in same query.

you can try this :
select jobtype, count(*) from your_table group by jobtype
union
select 'My Total', count(*) from your_table;
This will give result like(based on your table):
IT 5
Admin 10
Myv Total 15

You could create 2 int variables
$SQL = mysql_query('SELECT * FROM table');
$jobLookingFor = 'programmer';
$jobTypeSameCount = 0;
$jobTotalNumber = 0;
while($result = mysql_fetch_array($SQL))
{
if($result['jobtype'] === $jobLookingFor)
{
$jobTypeSameCount = $jobTypeSameCount + 1;
}
$jobTotalNumber = $jobTotalNumber + 1;
}
That is off the top of my head, so excuse the spelling mistakes.
after the while loop has completed
the jobTypeSameCount will be the number of the same jobs you are searching for
the jobTotalNumber will be the total rows including both the similar and other job type rows.
EDIT: Try this solution from a simillar question
SELECT COL_1, COL_2, COL_3, COL_4, COUNT(*)
FROM MyTable
GROUP BY COL_1, COL_2, COL_3, COL_4
If you ever want to weed out rows that don't have a duplicate:
SELECT COL_1, COL_2, COL_3, COL_4, COUNT()
FROM MyTable
GROUP BY COL_1, COL_2, COL_3, COL_4
HAVING COUNT() > 1
at: How to find duplicate count among several columns?

try this:
SELECT COUNT(*) AS same_duplicate_jobs ,job_type ,total_jobs = ( SELECT COUNT(*) FROM jobs) FROM jobs GROUP BY job_type HAVING COUNT(*) > 1

Related

Count number of times that columns A & B contain values that also appear in column B & A

In my database, I have a table with those values :
column_a,column_b
1,2
3,4
2,1
4,3
3,1
5,6
1,4
1,3
I'm able to know how many times there's a match between a specific value, and any other value. Take value "1" :
SELECT COUNT(*) FROM (SELECT * FROM `table` WHERE `column_a` = 1) as T1
JOIN (SELECT * FROM `table` WHERE `column_b` = 1) as T2
WHERE T1.`column_b` = T2.`column_a`
Resultat will be 2, because we have 1,2, 2,1, 1,3 and 3,1 -> 1 matches with 2 and 3.
Now, I want to know the total number of matches. Here, it will be 3 (because there's 3,4 and 4,3).
Does anyone have and idea?
Thank you
One way to solve this is to count all the cases where a matching pair is found but restricting the matches such that only the pair where column_ais greater than column_b is selected to avoid duplication:
SELECT COUNT(*)
FROM `table` t1
WHERE EXISTS (
SELECT *
FROM `table` t2
WHERE t2.column_b = t1.column_a AND t2.column_a = t1.column_b
AND t2.column_a < t1.column_a
)
Output:
3
Demo on SQLFiddle
You can also use least() & greatest() function :
SELECT COUNT(*)
FROM (SELECT COUNT(*)
FROM `table` t1
GROUP BY LEAST(column_a, column_B), GREATEST(column_a, column_B)
HAVING COUNT(*) > 1
) t;
Here is a demo.
Here is one method:
select count(distinct case when a = 1 then b else a end)
from t
where 1 in (a, b);
Here is a db<>fiddle.

update row if count(*) > n

my DB has this structure:
ID | text | time | valid
This is my current code. I'm trying to find a way to do this as one query.
rows = select * from table where ID=x order by time desc;
n=0;
foreach rows{
if(n > 3){
update table set valid = -1 where rows[n];
}
n++
}
I'm checking how many rows exist for a given ID. Then I need to set valid=-1 for all rows where n >3;
Is there a way to do this with one query?
You can use a subquery in the WHERE clause, like this:
UPDATE table
SET valid=-1
WHERE (
SELECT COUNT(*)
FROM table tt
WHERE tt.time > table.time
AND tt.ID = table.ID
) > 3
The subquery counts the rows with the same ID and a later time. This count will be three or less for the three latest rows; the remaining ones would have a greater count, so their valid field would be updated.
Assuming that (id,time) has a UNIQUE constraint, i.e. no two rows have the same id and same time:
UPDATE
tableX AS tu
JOIN
( SELECT time
FROM tableX
WHERE id = #X -- the given ID
ORDER BY time DESC
LIMIT 1 OFFSET 2
) AS t3
ON tu.id = #X -- given ID again
AND tu.time < t3.time
SET
tu.valid = -1 ;
update table
set valid = -1
where id in (select id
from table
where id = GIVEN_ID
group by id
having count(1) >3)
Update: I really like dasblinkenlight's solution because is very neat, but I wanted to try also to do it in my way, a quite verbose one:
update Table1
set valid = -1
where (id, time) in (select id,
time
from (select id,time
from table1
where id in (select id
from table1
group by id
having count(1) >3)
-- and id = GIVEN_ID
order by time
limit 3, 10000000)
t);
Also in SQLFiddle
to do it for all ids, or only for one if you set a where in the a subquery
UPDATE TABLE
LEFT JOIN (
SELECT *
FROM (
SELECT #rn:=if(#prv=id, #rn+1, 1) AS rId,
#prv:=id AS id,
TABLE.*
FROM TABLE
JOIN ( SELECT #prv:=0, #rn:=0 ) tmp
ORDER BY id, TIMESTAMP
) a
WHERE rid > 3
) ordered ON ordered.id = TABLE.id
AND ordered.TIMESTAMP = TABLE.TIMESTAMP
AND ordered.text = TIMESTAMP.text
SET VALID = -1
WHERE rid IS NOT NULL

Count duplicates records in Mysql table?

I have table with, folowing structure.
tbl
id name
1 AAA
2 BBB
3 BBB
4 BBB
5 AAA
6 CCC
select count(name) c from tbl
group by name having c >1
The query returning this result:
AAA(2) duplicate
BBB(3) duplicate
CCC(1) not duplicate
The names who are duplicates as AAA and BBB. The final result, who I want is count of this duplicate records.
Result should be like this:
Total duplicate products (2)
The approach is to have a nested query that has one line per duplicate, and an outer query returning just the count of the results of the inner query.
SELECT count(*) AS duplicate_count
FROM (
SELECT name FROM tbl
GROUP BY name HAVING COUNT(name) > 1
) AS t
Use IF statement to get your desired output:
SELECT name, COUNT(*) AS times, IF (COUNT(*)>1,"duplicated", "not duplicated") AS duplicated FROM <MY_TABLE> GROUP BY name
Output:
AAA 2 duplicated
BBB 3 duplicated
CCC 1 not duplicated
For List:
SELECT COUNT(`name`) AS adet, name
FROM `tbl` WHERE `status`=1 GROUP BY `name`
ORDER BY `adet` DESC
For Total Count:
SELECT COUNT(*) AS Total
FROM (SELECT COUNT(name) AS cou FROM tbl GROUP BY name HAVING cou>1 ) AS virtual_tbl
// Total: 5
why not just wrap this in a sub-query:
SELECT Count(*) TotalDups
FROM
(
select Name, Count(*)
from yourTable
group by name
having Count(*) > 1
) x
See SQL Fiddle with Demo
The accepted answer counts the number of rows that have duplicates, not the amount of duplicates. If you want to count the actual number of duplicates, use this:
SELECT COALESCE(SUM(rows) - count(1), 0) as dupes FROM(
SELECT COUNT(1) as rows
FROM `yourtable`
GROUP BY `name`
HAVING rows > 1
) x
What this does is total the duplicates in the group by, but then subtracts the amount of records that have duplicates. The reason is the group by total is not all duplicates, one record of each of those groupings is the unique row.
Fiddle: http://sqlfiddle.com/#!2/29639a/3
SQL code is:
SELECT VERSION_ID, PROJECT_ID, VERSION_NO, COUNT(VERSION_NO) AS dup_cnt
FROM MOVEMENTS
GROUP BY VERSION_NO
HAVING (dup_cnt > 1 && PROJECT_ID = 11660)
I'm using this query for my own table in PHP, but it only gives me one result whereas I'd like to the amount of duplicate per username, is that possible?
SELECT count(*) AS duplicate_count
FROM (
SELECT username FROM login_history
GROUP BY username HAVING COUNT(time) > 1
) AS t;

Deselecting a data with different column value

Hi guys I've got this table structure
field 1 field 2
---------------------------------------------
1 1
1 2
2 1
Then I want it to be like this when selecting Key Field2 = 1
field 1 field 2
---------------------------------------------
2 1
I don't want to return field1 = 1 because It contains different values field1 IN (1,2)
Thanks you so much.
Your post seems unclear because I think you mixed up column names in certain parts of your description. However, judging by your sample output, I'm going to assume you mean the following:
Select rows from the table where field2 contains identical values for the same field1.
If you only need to output field1 and field2, you could do the following:
SELECT field1, MAX(field2) AS field2
FROM atable
GROUP BY field1
HAVING COUNT(DISTINCT field2) = 1
You can omit DISTINCT if your table cannot hold duplicate pairs of (field1, field2).
However, if there are more columns in the table and some or all of them need to be returned too, you could first just get the field1 values like above, then join that row set back to atable to get complete rows, like this:
SELECT t.* /* or specify the necessary columns explicitly */
FROM atable AS t
INNER JOIN (
SELECT field1
FROM atable
GROUP BY field1
HAVING COUNT(DISTINCT field2) = 1
) s ON t.field1 = s.field1
Again, DISTINCT can be omitted, as explained above.
Since you are using SQL Server 2008, you could also use windowed aggregating. If your table doesn't contain duplicates of (field1, field2), you could use the following:
;
WITH counted AS (
SELECT
*,
cnt = COUNT(*) OVER (PARTITION BY field1)
FROM atable
)
SELECT
field1,
field2,
…
FROM counted
WHERE cnt = 1
But if the duplicates are allowed, you'll need to use a slightly different approach, because there's no windowing counterpart for COUNT(DISTINCT …). Here's what you could try:
;
WITH counted AS (
SELECT
*,
f2min = MIN(field2) OVER (PARTITION BY field1),
f2max = MAX(field2) OVER (PARTITION BY field1)
FROM atable
)
SELECT
field1,
field2,
…
FROM minmaxed
WHERE f2min = f2max
That is, you are getting the minimum and the maximum value of field2 for every field1 value. Then you are filtering out rows where f2min is not the same as f2max, because that would imply that there are different field2 values in the group.
SELECT * FROM table WHERE field_2 = 1 AND field_1 <> 1

whats wrong with this mysql insert query?

insert into tblcustomermachine
(
select * from
((select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001' )
union all
(select Rate from tblmachine)) as t );
that table contains 18 cols and this resultset also contains 18 rows yet it shows " Column count doesn't match value count at row 1" . why?
It looks like your table tblcustomermachine has more then the 1 column.
Like Simone answered, update your insert to INSERT INTO tblcustomermachine(col_1) SELECT ...
You may skip the column names during INSERT, however the SELECT needs to return the same amount of columns that the table holds.
AFAIK, you have to declare field name:
insert into tblcustomermachine (col_1, col_2, col_3, ... col_18) (
select t.field1, t.field2, t.field3, ... t.field18 from (
(select vch_CustomerID from tblcustomer where tblcustomer.vch_CustomerID='Cust00001')
union all (select Rate from tblmachine))
as t
);