如何在sql中编写更新语句

时间:2015-11-17 17:39:24

标签: sql teradata

我有一个只有两列master_id和一个group id列的表。数据如下所示

master_id   group_id
---------   --------
  M1          G1
  M2          G1
  M2          G2
  M3          G2
  M4          G3

....等等。

我需要编写一个更新语句,选择所有没有group_id G1的master_id(即M2,M3和M4),如果其中任何一个都是G1组的一部分(M2也有G1组ID)然后更新该组(M2和M3属于同一组)以具有组ID G1。 即更新后应该

master_id   group_id
---------   --------
  M1          G1
  M2          G1
  M2          G1
  M3          G1
  M4          G3

如何在sql中执行相同操作?

到目前为止我尝试过的是

Update dw_stuart_tbls.intrnl_cdc_id
FROM
(
  SELECT cnst_mstr_id
  FROM dw_stuart_tbls.intrnl_cdc_id
  WHERE group_id NOT LIKE '%G1%'
  AND cnst_mstr_id NOT IN 
  ( SELECT cnst_mstr_id
  FROM dw_stuart_tbls.intrnl_cdc_id
  WHERE group_id LIKE '%G1%'))upd_tbl

请建议一种方式。

1 个答案:

答案 0 :(得分:0)

我不知道Teradata是什么,但您可以通过子选择完成所需的操作,以获得master_id group_id G2的所有UPDATE whatever SET group_id = 'G1' WHERE master_id IN ( SELECT DISTINCT master_id FROM whatever WHERE group_id = 'G2' );

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "michaelb/laravel-db2": "~2.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

SQLFiddle