我正在使用SQL Server 2012
并且我有以下T-SQL
查询:
SELECT a.ResaID,
b.CheckInDate,
c.ProfileID
FROM RSD a
LEFT JOIN GSS b on b.ResaID = a.ResaID
LEFT JOIN RS c on c.ResaID = a.ResaID
LEFT JOIN Profile d on d.ProfileID = c.ProfileID
上述查询输出的摘录如下所示:
ResaID CheckInDate ProfileID
100 2018-03-10 450
101 2018-03-15 658
102 2018-03-15 658
103 2018-03-24 700
115 2018-06-11 700
127 2018-07-09 851
我需要过滤此输出,以便它仅根据ProfileID
向我提供CheckInDate
唯一的记录。换句话说,具有相同ProfileID
和相同CheckInDate
的记录应仅出现一次(仅表示具有第一个ResaID
的记录)。具有相同ProfileID
但具有不同CheckInDate
的记录应完整显示(即,如果有2条记录,则输出将包括两条记录)。
根据上面给出的提取输出,所需的输出如下:
ResaID CheckInDate ProfileID
100 2018-03-10 450
101 2018-03-15 658
103 2018-03-24 700
115 2018-06-11 700
127 2018-07-09 851
我怎样才能做到这一点?
答案 0 :(得分:0)
尝试这样的事情
SELECT MIN(a.ResaID) AS FirstResaID,
b.CheckInDate,
c.ProfileID
FROM RSD a
LEFT JOIN GSS b on b.ResaID = a.ResaID
LEFT JOIN RS c on c.ResaID = a.ResaID
LEFT JOIN Profile d on d.ProfileID = c.ProfileID
GROUP BY c.ProfileID,b.CheckInDate;
我使用MIN()
来获取第一个 ResaID
- 假设这是IDENTITY
ID,较小的值是第一个一个。如果这是错误的,您需要sorting
规则来定义第一个。
答案 1 :(得分:0)
我认为你需要一个简单的GROUP BY
SELECT min(a.ResaID) ResaID,
b.CheckInDate,
c.ProfileID
FROM RSD a
LEFT JOIN GSS b on b.ResaID = a.ResaID
LEFT JOIN RS c on c.ResaID = a.ResaID
LEFT JOIN Profile d on d.ProfileID = c.ProfileID
group by
b.CheckInDate,
c.ProfileID
答案 2 :(得分:0)
您不使用个人资料表 你确定你需要离开吗?
SELECT min(a.ResaID),
b.CheckInDate,
c.ProfileID
FROM RSD a
JOIN GSS b on b.ResaID = a.ResaID
JOIN RS c on c.ResaID = a.ResaID
group by b.CheckInDate, c.ProfileID
简化版
DECLARE @T1 TABLE (id int primary key);
DECLARE @T2 TABLE (id int primary key, fk int);
INSERT INTO @T1
VALUES (1), (2), (3), (4);
INSERT INTO @T2
VALUES (1, 1), (2, 1), (3, 2), (4, 2);
SELECT t1.id as [t1.id], t2.id as [t2.id], t2.fk as [t2.fk]
FROM @T1 T1
LEFT JOIN @T2 T2
ON t1.ID = t2.fk;
SELECT min(t1.ID) as minT1, t2.fk
FROM @T1 T1
LEFT JOIN @T2 T2
ON t1.ID = t2.fk
GROUP BY t2.fk;
SELECT min(t1.ID) as minT1, t2.fk
FROM @T1 T1
JOIN @T2 T2
ON t1.ID = t2.fk
GROUP BY t2.fk;