我有一个查询,我每季度都在运行,提取有关某些医疗问题的患者访问诊所的数据。查询运行正常,但我刚被要求添加性别字段,以便我们可以按男性和女性过滤患者并查看任何结果模式。我一直用于其余患者数据的人口统计表已经有一个性别列,所以我只是将它添加到我的查询中,但是当我去运行它时,我得到一个“无效的列名称”错误而且我没有不知道为什么。
由于我只需要显示患者ID,姓名,访问位置以及现在的性别,我一直在使用子查询来获取我需要过滤患者列表所需的其他数据。这就是我所拥有的:
SELECT DISTINCT
[MedHist: Patient ID] as [Patient ID],
[Patient: First Last Name] as [Patient Name],
[Patient: Gender] as [Gender],
ServiceLocationID as [Service Location]
FROM
(SELECT DISTINCT
mh.[MedHist: Patient ID],
d.[Patient: First Last Name],
d.[Patient: Date of Birth],
d.[Patient: Gender] as [Gender],
d.[Patient: Age],
a.Status,
mh.[MedHist: Procedure Code],
pm.Description,
v.ServiceLocationID
FROM MedicalHistory mh INNER JOIN Demographics d ON mh.[MedHist: Patient ID] = d.[Patient: Patient ID]
INNER JOIN Appointment a ON a.PatientID = d.[Patient: Patient ID]
JOIN Visit v ON v.PatientID = d.[Patient: Patient ID]
JOIN PatientMeds pm ON pm.PatientID = d.[Patient: Patient ID]
WHERE d.[Patient: Age] ...is in a certain range
AND a.Status ...is a certain thing
AND pm.Description ...involves a certain medication
AND some other stuff
) Demographics
正如我所提到的,在我添加Gender字段之前,这个查询运行得很好,现在我在初始[Patient: Gender]
语句的SELECT
部分下面有一个红色的波形,它给了我无效列名错误。有什么想法吗?
答案 0 :(得分:0)
您可能认为该列位于人口统计表中,但事实并非如此。
最可能的原因(在这种情况下)是拼写错误。如果我不得不猜测,在“性别”之前或之后,名称中还有其他空格。
查找列实际名称的一种方法是查看information_schema.columns
:
select '|' + column_name + '|'
from information_schema.columns
where table_name = 'Demographics' and
lower(column_name) like '%gender%';
答案 1 :(得分:0)
如果您将FROM表命名为t1,则应根据此(dinamic)tablename命名列中的列
SELECT DISTINCT
[t1: Patient ID] as [Patient ID],
[t1: First Last Name] as [Patient Name],
[t1: Gender] as [Gender],
[t1: ServiceLocationID as [Service Location]
FROM
(SELECT DISTINCT
mh.[MedHist: Patient ID],
d.[Patient: First Last Name],
d.[Patient: Date of Birth],
d.[Patient: Gender],
d.[Patient: Age],
a.Status,
mh.[MedHist: Procedure Code],
pm.Description,
v.ServiceLocationID
FROM MedicalHistory mh INNER JOIN Demographics d ON mh.[MedHist: Patient ID] = d.[Patient: Patient ID]
INNER JOIN Appointment a ON a.PatientID = d.[Patient: Patient ID]
JOIN Visit v ON v.PatientID = d.[Patient: Patient ID]
JOIN PatientMeds pm ON pm.PatientID = d.[Patient: Patient ID]
WHERE d.[Patient: Age] ...is in a certain range
AND a.Status ...is a certain thing
AND pm.Description ...involves a certain medication
AND some other stuff
) t1
答案 2 :(得分:0)
更新:我正在回答我自己的问题,因为我发现了问题。
在我的子查询中,我在d.[Patient: Gender] as [Gender]
语句中有SELECT
(我通常会重命名这样的列,因为这个数据库中的很多表都有如此长的标题,这使得我的列不必要地变宽丑陋)。那么当我尝试在主查询中选择相同的[Patient: Gender]
字段时,系统无法找到它,因为它已在子查询中重命名。以下代码有效:
SELECT DISTINCT
[MedHist: Patient ID] as [Patient ID],
[Patient: First Last Name] as [Patient Name],
Gender,
ServiceLocationID as [Service Location]
FROM
(SELECT DISTINCT
mh.[MedHist: Patient ID],
d.[Patient: First Last Name],
d.[Patient: Date of Birth],
d.[Patient: Gender] as [Gender],
d.[Patient: Age],
a.Status,
mh.[MedHist: Procedure Code],
.....and so on