SQL根据多行信息创建一个黄金记录

时间:2015-07-13 19:13:12

标签: sql

在大多数情况下,SQL相当强大,当我遇到死墙时,通常是我的限制。这就是我今天所困扰的。

我桌子上有什么? What I have in my table ?

输出应该是什么样的? What output should look like ?

到目前为止我得到了什么?

    WITH tempTable AS (
SELECT
    EID,
    Gender,
    NameLast,
    NameFirst,
    NameMiddle,
    AddrStreet1,
    AddrStreet2,
    City,
    State,
    Zip,
    Country,
    SSN,
    DOB,
    HomePhnAreaCode,
    HomePhnNumber,
    CellPhnAreaCode,
    CellPhnNumber,
    ROW_NUMBER() OVER (PARTITION BY EID ORDER BY ModifiedDate DESC) AS RowNum
FROM
    [Database].[dbo].[OriginalTable]
)

UPDATE TABLE [Database].[dbo].[SecondaryTable] SET col1, col2, col3....
SELECT
    EID,
    MAX (Gender)    AS  Gender,
    MAX (NameLast)  AS  NameLast,
    MAX (NameFirst) AS  NameFirst,
    MAX (NameMiddle)    AS  NameMiddle,
    MAX (AddrStreet1)   AS  AddrStreet1,
    MAX (AddrStreet2)   AS  AddrStreet2,
    MAX (City)  AS  City,
    MAX (State) AS  State,
    MAX (Zip)   AS  Zip,
    MAX (Country)   AS  Country,
    MAX (SSN)   AS  SSN,
    MAX (DOB)   AS  DOB,
    MAX (HomePhnAreaCode)   AS  HomePhnAreaCode,
    MAX (HomePhnNumber) AS  HomePhnNumber,
    MAX (CellPhnAreaCode)   AS  CellPhnAreaCode,
    MAX (CellPhnNumber) AS  CellPhnNumber
FROM
    tempTable
GROUP BY
    EID

到目前为止,这种方法似乎不起作用。 你们中的一些人能否就如何做到这一点找到正确的方向!?

1 个答案:

答案 0 :(得分:0)

如果速度不重要,你可以尝试一下天真的"像这样的方法

SELECT
(SELECT TOP(1) firstCol FROM YourTable WHERE firstCol IS NOT NULL ORDER BY someCol) AS firstCol,
(SELECT TOP(1) secondCol FROM YourTable WHERE secondCol IS NOT NULL ORDER BY someCol) AS secondCol,
(SELECT TOP(1) thirdCol FROM YourTable WHERE thirdCol IS NOT NULL ORDER BY someCol) AS thirdCol 
...

据我所知,没有汇总功能可以让你选择" /"选择"使用GROUP BY时,列中具有某些属性的值(例如" not null")。 (加上它不会是"聚合"再加上)