如何将交叉表查询合并为一行?访问2007

时间:2011-08-24 18:12:18

标签: sql ms-access

我有一个包含多个感兴趣属性的交叉表查询。在该查询中,特定属性的存在是是或否(1 =是0 =否)。现在,如果一个人有两个属性,那么它们在数据集中由两行表示。如果他们有三个问题,那么它们由三行代表。我需要一种方法让多个属性显示在同一行。例如,如果他们患有糖尿病和烟草,那么在该列下面会有一行“1”,而不是现在的那一行,其中有1,其次是全部为糖尿病的零。除了烟草(它是一个烟草)之外,“烟草”排在每一列都有0。

table (Click to enlarge)

是输出外观的屏幕截图。无论他们有多少问题,我每个病人只需要一排。

下面是我的sql。

TRANSFORM IIf([tblComorbidity.comorbidityexplanation]=[tblComorbidity.comorbidityexplanation],1,0) AS Morbidity
SELECT
  Person.PersonID,
  Person.Age,
  tblKentuckyCounties.Metro,
  tblKentuckyCounties.Appalachian,
  Person.asiaAdmit,
  Person.Sex
FROM tblKentuckyCounties
  INNER JOIN (tblComorbidity
    INNER JOIN (Person
      INNER JOIN tblComorbidityPerson ON Person.PersonID = tblComorbidityPerson.personID
    ) ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK
  ) ON tblKentuckyCounties.ID = Person.County
WHERE (((tblComorbidity.comorbidityexplanation)="anxiety and depression"
     Or (tblComorbidity.comorbidityexplanation)="heart"
     Or (tblComorbidity.comorbidityexplanation)="respiratory"
     Or (tblComorbidity.comorbidityexplanation)="uti"
     Or (tblComorbidity.comorbidityexplanation)="diabetes"
     Or (tblComorbidity.comorbidityexplanation)="hypertension"
     Or (tblComorbidity.comorbidityexplanation)="tobacco"))
GROUP BY
  Person.PersonID,
  Person.Age,
  tblKentuckyCounties.Metro,
  tblKentuckyCounties.Appalachian,
  Person.asiaAdmit,
  Person.Sex,
  tblKentuckyCounties.Appalachian,
  tblKentuckyCounties.Metro,
  tblComorbidity.comorbidityexplanation
PIVOT tblComorbidity.comorbidityexplanation;

1 个答案:

答案 0 :(得分:1)

如果某人有两次超过1个条件并尝试清理某些格式,则将值更改为项目数。在我的有限测试中它可以工作,但可能需要一些调整,因为我没有你的数据,但它应该让你开始。

TRANSFORM nz(Count([tblComorbidity.comorbidityexplanation]),0) AS Morbidity

SELECT Person.PersonID, Person.Age, tblKentuckyCounties.Metro, tblKentuckyCounties.Appalachian, Person.asiaAdmit, Person.Sex

FROM tblKentuckyCounties INNER JOIN (tblComorbidity INNER JOIN (Person INNER JOIN tblComorbidityPerson ON Person.PersonID = tblComorbidityPerson.personID) ON tblComorbidity.ID = tblComorbidityPerson.comorbidityFK) ON tblKentuckyCounties.ID = Person.County

WHERE tblComorbidity.comorbidityexplanation IN ('anxiety and depression', 'heart', 'respiratory', 'uti', 'diabetes', 'hypertension', 'tobacco')

GROUP BY Person.PersonID, Person.Age, tblKentuckyCounties.Metro, tblKentuckyCounties.Appalachian, Person.asiaAdmit, Person.Sex

PIVOT tblComorbidity.comorbidityexplanation;