[英]Compare two columns in SQL
我是 SQL 新手,在 GCP 中有非常基本的查詢。
讓我們考慮下表:
姓名 | 乙 | C |
---|---|---|
阿倫 | 1234-5678 | 1234 |
塔拉 | 6789 - 7654 | 6789 |
阿倫 | 4567 | 4324 |
在這里,我想比較 B 列和 C 列,如果它們匹配,則在same
的列中給出 1 else 0,否則在different
的列中給出(我們必須創建)。
所以這里的問題:
B
列有1234-5678
並且C
列有1234
,則該列應僅考慮值中“-”之前的數字匹配。輸出應該是:
姓名 | 乙 | C | 相同的 | 不同的 |
---|---|---|---|---|
阿倫 | 1234-5678 | 1234 | 1 | 0 |
塔拉 | 6789 - 7654 | 6789 | 1 | 0 |
阿倫 | 4567 | 4324 | 0 | 1 |
另外,我想為same
和different
列的Name
中的每個值計算 1 的值。
到目前為止,我已經嘗試過:
SELECT
name,
b,
c ,
if(b = c, 1, 0) as same,
if (b!=c,1,0) as different,
count(same),
count(different)
From Table
使用“MySQL” (與 SQL 服務器幾乎相同)這是可能的解決方案。
CREATE TABLE Users (
Name varchar(50),
B varchar(50),
C varchar(50)
);
INSERT INTO Users
VALUES
('Arun', '1234-5678', '1234'),
('Tara', '6789-7654', '6789'),
('Arun', '4567', '4324');
same
和different
列SELECT
Name, B, C,
CASE WHEN SUBSTRING_INDEX(B, "-", 1) = C THEN 1 ELSE 0 END as same,
CASE WHEN SUBSTRING_INDEX(B, "-", 1) <> C THEN 1 ELSE 0 END as different
FROM
Users
total_same
和total_different
SELECT
Name,
SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) = C THEN 1 ELSE 0 END) as total_same,
SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) <> C THEN 1 ELSE 0 END) as total_different
FROM
Users
GROUP BY Name
第一步,您需要對列 b 進行SUBSTR 。 我們從位置 1 開始,我們想要 4 個字符(僅當 '-' 之前只有 4 個字符時才有效)。
With table2 as (
select name, b,c, same, different from (select name, b, c, case when (SUBSTR(b,1,4) = c)
then '1' else '0' end as same, case when(SUBSTR(b,1,4)!= c) then '1' else '0' end as different
from Table1
group by name, b,c))
當您有復雜的查詢時,可以使用 WITH 子句,並且如果您想創建一個臨時表以便之后使用它。
Table2 給你這個:
在 WITH 子句之后,您將進行第二步,每個名稱的相同/不同計數:
Select table1.name,count(table2.same+table2.different) as total from table1
join table2 on (table2.name = table1.name and table2.b = table1.b)
group by table1.name;
輸出為您提供每個名稱的總數(名稱是分組依據,因此在您的示例中,您將只有 2 行,一個用於 Arun,總共 2 行(相同 + 不同),另一行總共 1)
所以這是整個代碼:
with table2 as (
select name, b,c, same, different from (select name, b, c, case when (SUBSTR(b,1,4) = c) then '1' else '0' end as same, case when(SUBSTR(b,1,4)!= c) then '1' else '0' end as different
From Table1
group by name, b,c))
select table1.name, table1.b, table1.c, count(table2.same+table2.different) as total from table1
join table2 on (table2.name = table1.name and table2.b = table1.b)
group by table1.name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.