选择COUNT个相同的值,但不使用GROUP BY

时间:2019-06-25 12:47:38

标签: mysql

我想做一条SQL语句,在其中从表中获取所有数据,但是我想包括一个新列,该列对列中的相同值进行计数。 在这种情况下,我想在每一行中看到一列,该列计算相同的vin数字。 我尝试过

SELECT 
   *, 
   COUNT( DISTINCT vin) AS identical 
FROM table

但是它给了我一个错误: In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'table'; this is incompatible with sql_mode=only_full_group_by

目前,我无法修改数据库,而且我也不是100%确信更改sql_mode可以完成此操作。

+----+-----+---------+---------+---------+
| id | vin | status1 | status2 | status3 |
+----+-----+---------+---------+---------+
|  1 | 111 |       1 |       0 |       1 |
|  2 | 222 |       1 |       1 |       0 |
|  3 | 333 |       0 |       1 |       0 |
|  4 | 333 |       0 |       1 |       1 |
|  5 | 333 |       0 |       0 |       1 |
|  6 | 222 |       1 |       1 |       0 |
+----+-----+---------+---------+---------+

我想看到这样的东西:

+----+-----+---------+---------+---------+-----------+
| id | vin | status1 | status2 | status3 | identical |
+----+-----+---------+---------+---------+-----------+
|  1 | 111 |       1 |       0 |       1 |         1 |
|  2 | 222 |       1 |       1 |       0 |         2 |
|  3 | 333 |       0 |       1 |       0 |         3 |
|  4 | 333 |       0 |       1 |       1 |         3 |
|  5 | 333 |       0 |       0 |       1 |         3 |
|  6 | 222 |       1 |       1 |       0 |         2 |
+----+-----+---------+---------+---------+-----------+

3 个答案:

答案 0 :(得分:5)

在MySQL 8+中,我们可以在此处使用COUNT作为分析函数:

SELECT
    id,
    vin,
    status1,
    status2,
    status3,
    COUNT(*) OVER (PARTITION BY vin) identical
FROM yourTable;

在早期版本的MySQL中,我们可以尝试加入一个子查询,该子查询可以找到vin个计数:

SELECT
    t1.id,
    t1.vin,
    t1.status1,
    t1.status2,
    t1.status3,
    t2.cnt AS identical
FROM yourTable t1
INNER JOIN
(
    SELECT vin, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY vin
) t2
    ON t1.vin = t2.vin;

答案 1 :(得分:0)

尝试这种方法:

select t.vin, t.status1 t.status2, t.status3, sq.identical from table t
left join (SELECT vin, 
   COUNT( *) AS identical 
FROM table
group by vin) as sq on sq.vin=t.vin

答案 2 :(得分:0)

您可以这样处理

SELECT `d`.*,(SELECT COUNT(*) FROM `data` WHERE `vin`=`d`.`vin`) AS `identical`
FROM `data` as `d` ;