[英]Select all rows that have the same value in two columns, while simultaneously having different values in another column?
I have a table where caretaker visits are recorded.我有一张记录看守访问的表格。 The table contains
caretakerCode
, patientID
, visitDate
and visitAddress
.该表包含
caretakerCode
、 patientID
、 visitDate
和visitAddress
。
I need to show all information from rows where the same caretaker went to more than one patient on the same day.我需要显示同一看护人在同一天去看望不止一名患者的行中的所有信息。 Here is an example.
这是一个例子。
caretakerCode patientID visitDate visitAddress
---------------------------------------------------------------
John Q 13 2022/01/13 27 Hamilton Rd
John Q 13 2022/01/14 27 Hamilton Rd
John Q 15 2022/01/14 101 Congress St
Melanie B 22 2022/01/15 3 Redroad Ct
In the example, the output would be在示例中,output 将是
caretakerCode patientID visitDate visitAddress
---------------------------------------------------------------
John Q 13 2022/01/14 27 Hamilton Rd
John Q 15 2022/01/15 101 Congress St
I have tried joins but I'm not sure how to make it take more than 2 columns.我试过加入,但我不确定如何让它占用超过 2 列。 Any help would be greatly appreciated!
任何帮助将不胜感激!
Thank you.谢谢你。
I think your example is wrong, since you wanted to achieve to show the visits on the same day.我认为你的例子是错误的,因为你想实现显示同一天的访问。 Your example shows 2 different days: 2022/01/14 and 2022/01/15.
您的示例显示了 2 个不同的日子:2022/01/14 和 2022/01/15。
Assume the table name is dbo.tVisits.假设表名是 dbo.tVisits。
USE tempdb;
CREATE TABLE dbo.tVisits
(
caretakerCode nvarchar(50) NOT NULL,
patientID int NOT NULL,
visitDate date NOT NULL,
visitAddress nvarchar(512) NOT NULL
);
INSERT INTO dbo.tVisits
(
caretakerCode,
patientID,
visitDate,
visitAddress
)
VALUES
( N'John Q', 13, '20220113', N'27 Hamilton Rd' ),
( N'John Q', 13, '20220114', N'27 Hamilton Rd' ),
( N'John Q', 15, '20220114', N'101 Congress St' ),
( N'Melanie B', 22, '20220115', N'3 Redroad Ct' );
;WITH CTE AS
(
SELECT
V.caretakerCode,
V.visitDate
FROM dbo.tVisits V
GROUP BY
V.caretakerCode,
V.visitDate
HAVING COUNT(*) > 1
)
SELECT
V.caretakerCode,
V.patientID,
V.visitDate,
V.visitAddress
FROM dbo.tVisits V
INNER JOIN CTE ON
CTE.caretakerCode = V.caretakerCode
AND CTE.visitDate = V.visitDate
ORDER BY 1,3,2;
caretakerCode![]() |
patientID![]() |
visitDate![]() |
visitAddress![]() |
---|---|---|---|
John Q![]() |
13 ![]() |
2022-01-14 ![]() |
27 Hamilton Rd![]() |
John Q![]() |
15 ![]() |
2022-01-14 ![]() |
101 Congress St![]() |
DROP TABLE IF EXISTS dbo.tVisits;
Explanation: In the Common Table Expression CTE you select rows where the same caretaker has multiple rows at the same visit date.解释:在公用表表达式 CTE中,您有 select 行,其中同一看护人在同一访问日期有多个行。 In the 2nd step you use this information on the original table to filter the rows by inner join.
在第二步中,您使用原始表上的此信息通过内部联接过滤行。
If this post answers your question, please do not forget to mark it as an answer.如果这篇文章回答了您的问题,请不要忘记将其标记为答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.