1

我有以下列:

ID,  Col1, Col2, Col3,  Col4
1    Bruce Wayne Gotham City
2    Daffy Duck  Sat on the pond
3    Bruce Wayne Gotham City

我需要做的是选择所有记录(ID,Col1-Col4)并显示每个条目有多少记录的计数。

SELECT Count(*) As Counter FROM TABLE

但我需要使用 Group By 来选择其余的列,所以:

SELECT (*) As Counter, ID,Col1,Col2,Col3,Col4 FROM TABLE Group By ID,Col1,Col2,Col3,Col4

但是,这会返回三个记录,每个记录的计数为 1 - 我所追求的是两个记录,一个计数为 2(布鲁斯韦恩)和一个计数为 1(达菲鸭)

** 更新。* *

结果将在 C# 数据网格中使用,显示所有四个列,我使用 ID 作为链接以进一步深入记录。

所以数据网格会显示,我总共有 3 条记录,点击数字将显示两条单独的记录 - 所以我想我需要比我之前说的更复杂的东西,因为我需要知道哪个 ID(正如您所提到的)链接到哪个记录。

因此,我是否需要进行嵌套选择,首先获得计数?

4

3 回答 3

1

如果要选择包含记录数的所有四列(id、col1、col2、col3),则必须从分组记录中选择其中一个 id。

例如,您可以选择Min(Id)/Max(Id)如下;

select count(*) counter, min(id) id, col1, col2, col3
from t
group by col1,col2,col3

SQL 提琴示例

| COUNTER | ID |        COL1 |   COL2 |     COL3 |
--------------------------------------------------
|       2 |  1 | Bruce Wayne | Gotham |     City |
|       1 |  2 |  Daffy Duck | Sat on | the pond |
于 2013-06-10T15:10:31.160 回答
0

If you need to select all records, then use a window function to get the count:

SELECT count(*) over (partition by Col1, Col2, Col3, Col4) as Counter,
       ID,Col1,Col2,Col3,Col4
 FROM TABLE;

If you want only two records, then you want a group by:

SELECT count(*) as Counter, Col1, Col2, Col3, Col4
FROM TABLE
group by Col1, Col2, Col3, Col4

The id is unique on each row, so each group consists of one row.

于 2013-06-10T14:51:01.230 回答
-1

Change the order in the GROUP BY clause:

GROUP BY Col1, Col2, Col3, Col4, ID

If you group by ID first, the two Bruce Wayne records are in different groups.

于 2013-06-10T14:50:28.477 回答