简体   繁体   English

SQL 列合并条件且不重复

[英]SQL column merge with conditions and without duplicates

Trying to combine 2 tables into 1 results table without having duplicate entries.试图将 2 个表组合成 1 个结果表而不具有重复条目。
Conditions are:条件是:
1. For each t1name look for each days in t2date, and if there is 1 in t2update, use that info. 1. 对于每个 t1name 查找 t2date 中的每一天,如果 t2update 中有 1,则使用该信息。 If there is no 1, then use the 0 row.如果没有 1,则使用 0 行。
2. If the t1name doesn't exist in t2name, create it with the t1date, and set t2update as 0. 2. 如果t2name中不存在t1name,则用t1date创建,t2update设置为0。

Here the are tables examples:这是表格示例:

| t1name | t1date     | t1department |
| ------ | ---------- | ------------ |
| name 1 | 2000.01.01 | tlc          | 
| name 1 | 2000.01.01 | tlc          |
| name 2 | 2000.01.04 | non-tlc      |
| name 3 | 2000.01.04 | non-tlc      |
| name 4 | 2000.01.04 | tlc          |
| name 5 | 2000.01.04 | tlc          |
| name 6 | 2000.01.04 | tlc          |
| name 7 | 2000.01.04 | tlc          |  

Table 1表格1

| t2name | t2update | t2date       |
| ------ | -------- | ------------ |
| name 1 | 1        | 2000.01.01   |
| name 1 | 0        | 2000.01.02   | 
| name 1 | 1        | 2000.01.02   | 
| name 2 | 1        | 2000.01.04   | 
| name 2 | 0        | 2000.01.04   | 
| name 2 | 0        | 2000.01.09   | 
| name 3 | 0        | 2000.01.09   | 
| name 3 | 1        | 2000.01.05   | 
| name 4 | 0        | 2000.01.03   |

Table 2表 2

| rname  | rupdate | rdate        |
| ------ | ------- | ------------ |
| name 1 | 1       | 2000.01.01   |
| name 1 | 1       | 2000.01.02   | 
| name 2 | 1       | 2000.01.04   | 
| name 3 | 0       | 2000.01.02   | 
| name 3 | 1       | 2000.01.05   | 
| name 4 | 0       | 2000.01.03   | 
| name 5 | 0       | 2000.01.09   | 
| name 6 | 0       | 2000.01.09   | 
| name 7 | 0       | 2000.01.09   | 

Results table结果表

Currently using following:目前使用以下:

CREATE OR REPLACE VIEW "rtable" AS 
(
   SELECT DISTINCT
      ((CASE WHEN (t2.t2updates) > 0) AND (MAX(t1.t1date))) THEN name
    , t1.date
    , t1.t1department
    , t2.updates 
FROM (table1 t1
LEFT JOIN table2 t2 on (t2.t2name = t1.t1name))
GROUP BY 
    , t1.date
    , t1.t1department
    , t2.updates
ORDER BY t1.t1name ASC
)

And the results return duplicate values per day.结果每天返回重复值。 For single t1name and t1date have both entries for 1 and 0. Need the outcome in a specific way so it I can do KPI on the updates of the VMs.对于单个 t1name 和 t1date 都有 1 和 0 的条目。需要以特定方式获得结果,以便我可以对 VM 的更新执行 KPI。

After simplifying the approach, and plenty of trials and error, simple right join did the job在简化方法并进行大量试验和错误之后,简单的右连接完成了工作

CREATE OR REPLACE VIEW "rtable" AS 
(
   SELECT
      t2.name
    , t2.date
    , t1.t1department
    , t2.updates 
FROM 
    (table1 t1
Right JOIN table2 t2 on (t2.t2name = t1.t1name) AND (t2.date = t1.date)))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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