That’s definitely a normalization problem. This is one of the most common mistakes in creating a database. If you’re doing much db work, read up on normal forms.
That’s why your setup is getting out of hand, it’s built wrong. See below.
You can probably use a pivot table for what you’re wanting on this job, although you’d have to update your code anytime you added new columns. (SQL doesn’t do dynamic columns in a PIVOT.) You can Google up tons of instructions for creating pivots.
Approximate code only, off the top of my head.
CREATE TABLE SURGINFO
(recordID int IDENTITY(1,1) PRIMARY KEY CLUSTERED, MRN char 10, SurgDate datetime, …)
CREATE TABLE CONDITIONS
(conditionID int IDENTITY(1,1) PRIMARY KEY CLUSTERED, ConditionName varchar 50, …)
CREATE TABLE SURGCOMPLICATIONS
(complicationID int IDENTITY(1,1) PRIMARY KEY CLUSTERED, recordID int REFERENCES SurgInfo(recordID), conditionID int REFERENCES Conditions(conditionID), conditionDate datetime, conditionNotes text, …)
INSERT SurgInfo (MRN, SurgDate) VALUES (‘123456’, ‘1/1/2009’)
INSERT SurgInfo (MRN, SurgDate) VALUES (‘987654’, ‘7/31/2009’)
say those have PK identity values 1 & 2
INSERT Conditions(ConditionName) VALUES (‘Pneumonia’)
INSERT Conditions(ConditionName) VALUES (‘Renal Failure’)
INSERT Conditions(ConditionName) VALUES (‘Infection’)
so those have identity values 1, 2, 3
Now you use that info to fill SurgComplications
INSERT SurgComplications(recordID, conditionID, conditionDate, conditionNotes)
VALUES(1,1,‘1/15/2009’,‘surg record 1, pneumonia, 15 days after surg’)
INSERT SurgComplications(recordID, conditionID, conditionDate, conditionNotes)
VALUES(2,2,‘6/01/2009’,‘surg record 1, renal, 6 months after surg’)
INSERT SurgComplications(recordID, conditionID, conditionDate, conditionNotes)
VALUES(2,1,‘10/15/2009’,‘surg record 2, pneumonia, 2 months after surg’)
The your query would be something like this, except a bit more complicated to pick up all your comparison fields. Google Common Table Expressions would be my best suggestion for writing these sorts of complex queries…
SELECT CN.ConditionName, count(SI.recordID)
FROM SurgInfo SI
inner join SurgComplications SC on SC.recordID = SI.recordID
inner join Conditions CN on CN.conditionID = SI.conditionID
WHERE SI.SurgDate between ‘1/1/2009’ and ‘12/31/2009’ and
DATEDIFF(‘dd’,SI.SurgDate,SC.ConditionDate) <= 30
GROUP BY CN.ConditionName
ORDER BY CN.ConditionName
That would get you a row for each Condition, with a count of the number of surgeries, for surgery dates in 2009 that got a complication within 30 days.
You would get one guy counted twice (for pneumonia & renal failure) unless you set up your query to prevent it. Depends on how you’re wanting your count, by condition or by person.