用于获取计数的SQL查询和具有多个记录的行

时间:2022-04-26 15:47:26

I'm trying to figure out the SQL query for SQL Server for this:

我正试图找出SQL Server的SQL查询:

TABLE:

表:

ID    AppointmentID    TypeID
------------------------------
1     1992             1
2     1992             1
3     1992             2
4     1993             1
...

Desired result:

期望的结果:

AppointmentID    TypeCount TypeID
---------------------------------
1992             2         1

I am only looking for the AppointmentID of TypeID = 1 which got the count of more than 1.

我只是在寻找TypeID = 1的AppointmentID,它的计数超过1。

Thanks,

谢谢,

2 个解决方案

#1


0  

Fiddle

小提琴

The table we have:

我们的表格:

CREATE TABLE appointments
(
    ID INT,
    AppointmentID INT,
    TypeID INT
);

Some data:

一些数据:

INSERT INTO appointments VALUES (1, 1992, 1);
INSERT INTO appointments VALUES (2, 1992, 1);
INSERT INTO appointments VALUES (3, 1992, 2);
INSERT INTO appointments VALUES (4, 1993, 1);

Query:

查询:

SELECT AppointmentID, count(*) AS TypeCount, TypeID FROM appointments
WHERE TypeID = 1
GROUP BY AppointmentID, TypeID
HAVING count(*) > 1;

#2


0  

USE THIS QUERY:

使用此查询:

SELECT AppointmentID, COUNT(*) as TypeCount, TypeID FROM YourTableName 
WHERE TypeID =1 
GROUP BY AppointmentID, TypeID  
HAVING COUNT(*) > 1

Replace YourTableName with actual table name

将YourTableName替换为实际的表名

#1


0  

Fiddle

小提琴

The table we have:

我们的表格:

CREATE TABLE appointments
(
    ID INT,
    AppointmentID INT,
    TypeID INT
);

Some data:

一些数据:

INSERT INTO appointments VALUES (1, 1992, 1);
INSERT INTO appointments VALUES (2, 1992, 1);
INSERT INTO appointments VALUES (3, 1992, 2);
INSERT INTO appointments VALUES (4, 1993, 1);

Query:

查询:

SELECT AppointmentID, count(*) AS TypeCount, TypeID FROM appointments
WHERE TypeID = 1
GROUP BY AppointmentID, TypeID
HAVING count(*) > 1;

#2


0  

USE THIS QUERY:

使用此查询:

SELECT AppointmentID, COUNT(*) as TypeCount, TypeID FROM YourTableName 
WHERE TypeID =1 
GROUP BY AppointmentID, TypeID  
HAVING COUNT(*) > 1

Replace YourTableName with actual table name

将YourTableName替换为实际的表名