如何在SQL中获取每个元素的最大值

发布于 2024-12-11 07:07:15 字数 626 浏览 0 评论 0原文

CREATE TABLE Department(
    DNumber integer NOT NULL PRIMARY KEY);

CREATE TABLE Patient(
    PID integer NOT NULL PRIMARY KEY,
    P_DNumber integer NOT NULL REFERENCES Department (DNumber)
);

CREATE TABLE Appointment(
    AppNumber integer NOT NULL PRIMARY KEY,
    AppDate date NOT NULL,
    App_DNumber integer  NOT NULL  REFERENCES Department (DNumber)
);

CREATE TABLE Attend(
    A_PID integer NOT NULL REFERENCES Patient (PID),
    A_AppNumber integer NOT NULL REFERENCES Appointment(AppNumber)
);

你好,我有这些表,我想找到每个 PID 他参加约会的最后日期。我尝试过连接,但没有任何效果。我正在使用 Postgres。有人对此有什么想法吗?

非常感谢

CREATE TABLE Department(
    DNumber integer NOT NULL PRIMARY KEY);

CREATE TABLE Patient(
    PID integer NOT NULL PRIMARY KEY,
    P_DNumber integer NOT NULL REFERENCES Department (DNumber)
);

CREATE TABLE Appointment(
    AppNumber integer NOT NULL PRIMARY KEY,
    AppDate date NOT NULL,
    App_DNumber integer  NOT NULL  REFERENCES Department (DNumber)
);

CREATE TABLE Attend(
    A_PID integer NOT NULL REFERENCES Patient (PID),
    A_AppNumber integer NOT NULL REFERENCES Appointment(AppNumber)
);

HEllo, I have these tables and I want to find for each PID the last Date he attended an appointment. I tried with joins but nothing worked. I am using Postgres. Does anyone have an idea about it?

Thank you very much

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾忌 2024-12-18 07:07:15

尝试一下,通过出席预约加入。

SELECT 
  Patient.PID,
  MAX(Appointment.AppDate) AS lastAttended
FROM 
  Patient 
  LEFT JOIN Attend ON Patient.PID = Attend.A_PID
  JOIN Appointment ON Appointment.AppNumber = Attend.A_AppNumber
GROUP BY Patient.PID

对于每月参加 2 次以上预约的患者,您需要在 HAVING 子句中添加 COUNT()

SELECT 
  Patient.PID,
  COUNT(Attend.A_AppNumber) AS numAppts
FROM 
  Patient 
  LEFT JOIN Attend ON Patient.PID = Attend.A_PID
GROUP BY Patient.PID
HAVING COUNT(Attend.A_AppNumber) >= 2

Give this a try, joining through Attend and Appointment.

SELECT 
  Patient.PID,
  MAX(Appointment.AppDate) AS lastAttended
FROM 
  Patient 
  LEFT JOIN Attend ON Patient.PID = Attend.A_PID
  JOIN Appointment ON Appointment.AppNumber = Attend.A_AppNumber
GROUP BY Patient.PID

For patients attending 2+ appointments per month you need COUNT() inside a HAVING clause.

SELECT 
  Patient.PID,
  COUNT(Attend.A_AppNumber) AS numAppts
FROM 
  Patient 
  LEFT JOIN Attend ON Patient.PID = Attend.A_PID
GROUP BY Patient.PID
HAVING COUNT(Attend.A_AppNumber) >= 2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文