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

时间:2017-07-26 09:10:27

标签: sql sql-server

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

TABLE:

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

期望的结果:

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

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

谢谢,

2 个答案:

答案 0 :(得分:0)

使用此查询:

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

将YourTableName替换为实际的表名

答案 1 :(得分:0)

Fiddle

我们的表格:

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

一些数据:

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);

查询:

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