---
# System prepended metadata

title: SQL 答題

---

# SQL 答題
>Q1: 共有那些部門，曾經有過資產? 請給我一個列表
請分別用 JOIN、子查詢 寫出來，並按照 部門代號 正序呈現
Ans:
欄位: 部門代號 / 部門中文
Q2: 取得日期(GETDATE)=今年，共有幾筆資產? 請給我一個數字
請把符合的資產加總起來
Ans:
欄位: 資產總數
Q3: 請列出大於一筆的資產，有那些部門? 請給我一個列表
請把符合的資產，通通列出來，並按照 資產數量 倒序呈現
Ans:
欄位: 部門代號 / 部門中文 / 資產數量
Q4: 請列出 符合以下條件 的資產有哪些? 請給我一個列表
請分別用 IN、Exists 寫出來，並按照 部門代號 倒序呈現
條件:
HR020.DIVISION=‘BB’
HR020.EFFECT_DT=‘20221001’
Ans:
欄位: 部門代號 / 部門中文

## Q1
1. 
``` SQL
SELECT HR.DPT AS '部門代號',HR.DPT_NAME AS '部門中文'
FROM HR020 AS HR
LEFT JOIN FA500 AS FA
ON FA.PUTDPT = HR.DPT
WHERE HR.DPT IN (select FA.PUTDPT from FA500)
GROUP BY HR.DPT,HR.DPT_NAME
ORDER BY HR.DPT
```
2. 
``` SQL
SELECT HR.DPT AS '部門代號',HR.DPT_NAME AS '部門中文'
FROM HR020 AS HR
WHERE HR.DPT IN (select FA500.PUTDPT from FA500 where FA500.PUTDPT = HR.DPT)
ORDER BY HR.DPT
```
## Q2
``` SQL
SELECT COUNT(FANO) AS '資產總數'
FROM FA500
WHERE SUBSTRING(GETDATE, 0,5) = '2023'
```

## Q3
``` SQL
SELECT HR.DPT AS '部門代號' , HR.DPT_NAME AS '部門中文 ',count(PUTDPT) AS '資產總數'
FROM FA500 AS FA
LEFT JOIN HR020 AS HR
ON FA.PUTDPT = HR.DPT
GROUP BY HR.DPT,HR.DPT_NAME,PUTDPT HAVING count(*) > 1
```
## Q4

1. 
``` SQL
select DPT,DPT_NAME from HR020 
where HR020.DPT IN (select FA500.PUTDPT from FA500) 
and HR020.DIVISION='BB'AND HR020.EFFECT_DT ='20221001' 
```
2. 
``` SQL
SELECT DPT,DPT_NAME FROM HR020 
WHERE EXISTS (
SELECT * FROM FA500 WHERE FA500.PUTDPT = HR020.DPT 
AND HR020.DIVISION='BB'AND HR020.EFFECT_DT ='20221001' )
```