iT邦幫忙

0

SQL如何用A欄判斷B欄是否有出現某資料且是唯一值?

請問交易明細如何用A欄去判對B欄是否有出現該資料,且只有一筆資料
例如:
https://ithelp.ithome.com.tw/upload/images/20190524/20117898r9IPWxRap1.jpg

需求,
只要列出該筆交易,只有賣出1個東西且分類要=211
(例如只列出像AA002這種的,AA001有賣211但是他還有其他品項,這種的就不用列出)

slime iT邦大師 1 級 ‧ 2019-05-24 22:57:22 檢舉
select b.* from ( select 發票號碼 from 交易明細資料 where count(發票號碼)=1 ) as a
join 交易明細資料 as b on a.發票號碼 = b.發票號碼

2 個回答

1
rogeryao
iT邦高手 7 級 ‧ 2019-05-25 01:06:38
最佳解答
SELECT table_a.*
FROM table_a 
INNER JOIN (
SELECT invoice_id
FROM table_a 
GROUP BY invoice_id
HAVING COUNT(invoice_id) = 1 
) AS TempTable ON TempTable.invoice_id=table_a.invoice_id
WHERE 1=1
AND category='211'

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=d6060a66f0078cb5f3161339f40645f9

0
paicheng0111
iT邦高手 2 級 ‧ 2019-05-24 23:07:37
SELECT invoice_id, item, category, name, count(invoice_id)
FROM table_a
GROUP BY invoice_id
HAVING count(invoice_id) = 1 AND category = 211

我要發表回答

立即登入回答