如何计算(SQL)中的行?

时间:2018-05-15 17:52:42

标签: mysql sql

我有两个表A,B和我的查询显示:(加入A和B)

select A.i,A.j,B.x,B.y,B.z from A inner join B on A.id=B.id_B order by A.i,A.j

+-----+-----+-----+-----+-----+
| A.i | A.j | B.x | B.y | B.z |
+=====+=====+=====+=====+=====+
|  bk | bg  |  1  | inf1| bar | 
+-----+-----+-----+-----+-----+
|  bk | bg  |  2  | inf2| bar | 
+-----+-----+-----+-----+-----+
|  bk | bg  |  3  | inf3|  y  | 
+-----+-----+-----+-----+-----+
|  ro | fn  |  5  | enf1| bar | 
+-----+-----+-----+-----+-----+
|  ro | fn  |  3  | enf2| bar | 
+-----+-----+-----+-----+-----+
|  st | st  |  3  | onf1| bar | 
+-----+-----+-----+-----+-----+

现在我想知道是多少次

  

A.I

重复,如:

    +-----+-----+-----+-----+-----+
    | A.i | A.j | B.x | B.y | B.z |RepeatColumn
    +=====+=====+=====+=====+=====+---
    |  bk | bg  |  1  | inf1| bar | 3 |(bk is repeated 3 times)
    +-----+-----+-----+-----+-----+---
    |  bk | bg  |  2  | inf2| bar | 3 |(bk is repeated 3 times)
    +-----+-----+-----+-----+-----+---
    |  bk | bg  |  3  | inf3|  y  | 3 |(bk is repeated 3 times)
    +-----+-----+-----+-----+-----+---
    |  ro | fn  |  5  | enf1| bar | 2 |(ro is repeated 2 times)
    +-----+-----+-----+-----+-----+---
    |  ro | fn  |  3  | enf2| bar | 2 |(ro is repeated 2 times)
    +-----+-----+-----+-----+-----+---
    |  st | st  |  3  | onf1| bar | 1 |(st is repeated once)
    +-----+-----+-----+-----+-----+---

我如何做这个查询,任何人都有任何想法?

5 个答案:

答案 0 :(得分:1)

您需要subquery

select A.i,A.j,
       B.x,B.y,B.z,
       (select count(*) from b where b.id = a.id) RepeatColumn
from A 
inner join B 
order by A.i,A.j;

但是,我在o / p中的表格(AB)之间找不到任何关系。所以,我只是在飞行中使用。

答案 1 :(得分:0)

编辑:不幸的是(对你而言)看起来MySQL并不支持简单的窗口函数。

像这样:

COUNT(1) OVER
  ( PARTITION BY A.i
  ) AS cnt

这取决于您的用例是否比您所显示的更复杂,如果值得拼凑group_concat变通方法,或者只是使用子查询来获取计数。

答案 2 :(得分:0)

从tablename中选择count(A.I);

答案 3 :(得分:0)

xcrun simctl addmedia

答案 4 :(得分:0)

尝试使用subquery

SELECT 
A.i,
A.j,
B.x,
B.y,
B.z,
(SELECT COUNT(1) FROM A as WHERE i = A.i) AS 'RepeatColumn'
FROM A 
INNER JOIN B 
ORDER BY A.i,A.j