简体   繁体   中英

How can I run this SQL Server code in POSTGRESQL?

Code in SQL Server:

SELECT
    a.ParcelID, a.PropertyAddress, 
    b.ParcelID, b.PropertyAddress,     
    ISNULL(a.PropertyAddress,b.PropertyAddress)
FROM
    PortfolioProject.dbo.NashvilleHousing a
JOIN 
    PortfolioProject.dbo.NashvilleHousing b ON a.ParcelID = b.ParcelID
                                            AND a.[UniqueID ] <> b.[UniqueID ]
WHERE
    a.PropertyAddress IS NULL

UPDATE a
SET PropertyAddress = ISNULL(a.PropertyAddress, b.PropertyAddress)
FROM PortfolioProject.dbo.NashvilleHousing a
JOIN PortfolioProject.dbo.NashvilleHousing b ON a.ParcelID = b.ParcelID
                                             AND a.[UniqueID ] <> b.[UniqueID ]
WHERE a.PropertyAddress IS NULL

Now, in PostgreSQL, I run the query like this:

SELECT 
  a.parcel_id, a.property_address, b.parcel_id, b.property_address, COALESCE(a.property_address, NULL, b.property_address, NULL) 
  FROM nashville_housing a
  JOIN nashville_housing b
    ON a.parcel_id = b.parcel_id
    AND a.unique_id <> b.unique_id
WHERE a.property_address IS NULL

The code above works, and shows me the rows of property_address that are null, and makes a new column COALESCE with the rows that I want to migrate to the column property_address .

UPDATE nashville_housing
SET property_address = COALESCE(a.property_address, NULL, b.property_address, NULL) 
FROM nashville_housing a
JOIN nashville_housing b
  on a.parcel_id = b.parcel_id
  AND a.unique_id <> b.unique_id
WHERE a.property_address IS NULL

Now, when I run this code, updates all the rows of the column property_address with the first match of COALESCE . I think is because I running COALESCE . When I check the function says: "The COALESCE function accepts an unlimited number of arguments. It returns the first argument that is not null. If all arguments are null, the COALESCE function will return null."

    SELECT 
      a.parcel_id, a.property_address, b.parcel_id, b.property_address, COALESCE(a.property_address, b.property_address)
      FROM nashville_housing a
      JOIN nashville_housing b
        ON a.parcel_id = b.parcel_id
        AND a.unique_id <> b.unique_id
    WHERE a.property_address IS NULL

UPDATE nashville_housing
SET property_address = COALESCE(nashville_housing.property_address, b.property_address)
FROM nashville_housing as b
WHERE nashville_housing.property_address IS NULL
AND nashville_housing.parcel_id = b.parcel_id
AND nashville_housing.unique_id <> b.unique_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM