1

我有一个非常大的、未标准化的表,我正在修复它。从那个大表中,我正在对数据进行规范化。我使用了 SQL 语句

INSERT INTO smallTable(patientID, admissionDate, dischargeDate)
select distinct patientID, admissionDate, dischargeDate
FROM largeTable

所以我的 smallTable 填充了正确的行数。还有另一列,drgCode我想添加到我的 smallTable 中。我尝试了以下查询来做到这一点

INSERT INTO smallTable(drgCode)
select drgCode from
(
SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable) as t

我收到的错误是cannot insert the value NULL into patientID, column does not alloq nulls, insert fails.

drgCode正确选择的唯一方法select distinct是使用查询的某些变体。当必须包含其他字段以缩小搜索范围时,如何仅插入一个字段。

我知道如果我清空我的 smallTable,我可以做到这一点,但我认为必须有办法解决它。

4

3 回答 3

5
    with    drg as (SELECT DISTINCT patientID, admissionDate, dischargeDate, drgCode from largeTable)
    update  s
    set     s.drgCode = l.drgCode
    from    smallTable s join drg l on 
                s.patientId = l.patientId and
                s.admissionDate = l.admissionDate and
                s.dischargeDate  = l.dischargeDate
于 2012-06-11T15:48:11.727 回答
2

根据我的理解,如果您在两个表中都有“PatientID”是唯一的,您可以执行以下操作。

Update S
SET S.drgCode = L.drgCode
FROM
    SmallTable S
INNER JOIN
    LargeTable T
   ON S.PatientID = T.PatientID

希望这可以帮助!!

于 2012-06-11T15:37:56.960 回答
1

当您对表执行插入操作时,查询中未指定的任何值都将填充为该列的默认值。如果列上没有默认值,将使用 NULL。您收到了该特定错误消息,因为您的列不允许 NULL 并且没有默认值。

鉴于您对 Praveen 的回复,也许您应该进一步规范化并将 drgCodes 放入单独的表中。

于 2012-06-11T15:50:02.000 回答