我有两张桌子TAB A和TAB B,我想打印 来自TAB A的所有内容以及如果记录存在于TAB B中,则返回1或0 但是在TAB B中可以是多个具有相同id的记录我想我需要将这个表分组?
TAB_A
╔══════╦══════╦══════╦════╗
║ COLA ║ COLB ║ COLC ║ ID ║
╠══════╬══════╬══════╬════╣
║ AAA ║ BBB ║ CAB ║ 1 ║
║ AAA ║ BBB ║ CFD ║ 2 ║
║ AAA ║ BBB ║ CCD ║ 3 ║
║ AAA ║ BBB ║ CTR ║ 4 ║
╚══════╩══════╩══════╩════╝
TAB_B
╔══════╦══════╦══════╦════╗
║ COLA ║ COLB ║ COLC ║ ID ║
╠══════╬══════╬══════╬════╣
║ AAA ║ BBB ║ CAB ║ 1 ║
║ AAA ║ BBB ║ CFD ║ 2 ║
║ AAA ║ BBB ║ CCD ║ 3 ║
║ AAA ║ BBB ║ CCD ║ 3 ║
║ AAA ║ BBB ║ CCD ║ 3 ║
║ AAA ║ BBB ║ CTR ║ 4 ║
║ AAA ║ BBB ║ CTR ║ 5 ║
╚══════╩══════╩══════╩════╝
通过这个例子,我应该有4条记录,但LEFT JOINT给出了6条
SELECT
A.*
, case when B.ID is not null then 1 else 0 end as NEW_COLUMN
FROM
TAB_A A
left join TAB_B B
on A.ID= B.ID
WHERE
SOMETHING ....
答案 0 :(得分:2)
您可以使用DISTINCT
关键字删除TAB_B
表格中可能存在的重复项。
SELECT DISTINCT A.*,
CASE WHEN B.ID IS NOT NULL THEN 1 ELSE 0 END AS NEW_COLUMN
FROM TAB_A A LEFT JOIN TAB_B B ON A.ID = B.ID
答案 1 :(得分:1)
您只在TABA上运行查询,但在子查询中,您可以决定是否在TABB中存在记录,这样您就可以返回1或0(如您所愿)
试试这个:
SELECT *,
CASE
WHEN
(SELECT COUNT(*) FROM TABB
WHERE TABB.ID = TABA.ID) > 0
THEN 1
ELSE 0
END
FROM TABA
答案 2 :(得分:1)
您可以将ROW_NUMBER()
与PARTITION BY
子句一起使用。
试试这个
SELECT * FROM
(
SELECT A.* ,
CASE WHEN B.ID IS NOT NULL THEN 1
ELSE 0
END AS NEW_COLUMN,
ROW_NUMBER() OVER(PARTITION BY B.ID ORDER BY B.ID) AS row_num
FROM TAB_A A
LEFT JOIN TAB_B B ON A.ID = B.ID
) res
WHERE res.row_num = 1