我是sql查询的初学者,我想问一个问题。
我有2个表,即dbo.Group_Master和dbo.Group_Assign。
TABLE : GROUP MASTER
| GROUP_ID | GROUP_DESC |
|------------ |:---------------: |
| PMD | POWER MOTOR |
| ASSY | ASSEMBLY |
| FINANCE | FINANCE DEPT |
| COSTING | COSTING DEPT |
| IE | IMPORT EXPORT |
| BBC GROUP | BBC GROUP |
| PRODUCTION | PRODUCTION DEPT |
| PURCHASING | PURCHASING |
| SALE | SALE DEPT |
| MMASTER | MATERIAL MASTER |
TABLE : GROUP_ASSIGN
| JOB_ID | STEP_ID | LOG_NAME | GROUP_ID |
|-------- |:-------: |---------- |---------- |
| J1 | 1 | ACCOUNT | PMD |
| J1 | 2 | ACCOUNT | ASSY |
| J1 | 3 | ACCOUNT | SALE |
| J1 | 1 | FREIGHT | IE |
当我加入两个表并放入where子句时,运行如下的查询
SELECT
a.GROUP_ID,
a.GROUP_DESC,
CASE WHEN b.GROUP_ID IS NULL THEN '0' ELSE '1' end as status
FROM dbo.GROUP_MASTER A
LEFT JOIN dbo.GROUP_ASSIGN B ON (B.GROUP_ID = a.GROUP_ID)
WHERE B.LOG_NAME LIKE 'ACCOUNT'
我想要的是结果管理显示所有前2列,只有第3列受where子句影响,如下图所示。我有什么方法可以做到吗?
答案 0 :(得分:0)
尝试以下查询...
SELECT
A.GROUP_ID,
A.GROUP_DESC,
CASE WHEN B.GROUP_ID IS NULL THEN '0' ELSE '1' end as status
FROM dbo.GROUP_MASTER A
LEFT JOIN (SELECT * FROM dbo.GROUP_ASSIGN WHERE LOG_NAME LIKE 'ACCOUNT') B ON (A.GROUP_ID = B.GROUP_ID)
答案 1 :(得分:0)
您可以尝试使用子查询(首先从group_assign中获取您想要的内容),如下所示:
SELECT
a.GROUP_ID,
a.GROUP_DESC,
CASE WHEN b.GROUP_ID IS NULL THEN '0' ELSE '1' end as status
FROM dbo.GROUP_MASTER A
LEFT JOIN (select GROUP_ID, LOG_NAME from dbo.GROUP_ASSIGN where LOG_NAME LIKE 'ACCOUNT') B ON (B.GROUP_ID = a.GROUP_ID)