我需要一些sql查询帮助。
我有一张表是dbo.invoice。
| PO_NO | TYPE | MOVEMENT_TYPE | QUANTITY | SALESREF | FLOW |
|---------- |----------- |--------------- |---------- |---------- |------ |
| 10001001 | G.RECEIPT | 101 | 1000.00 | 5001 | S |
| 10001001 | G.RECEIPT | 101 | 2000.00 | 5002 | S |
| 10001001 | G.RECEIPT | 122 | 1000.00 | 5001 | H |
| 10001001 | G.RECEIPT | 122 | 1500.00 | 5002 | H |
| 10001001 | INVOICE | | 1000.00 | 5001 | S |
| 10001001 | INVOICE | | 2000.00 | 5002 | S |
| 10001001 | INVOICE | | 1500.00 | 5002 | H |
我想要的输出是显示Type = G.RECEIPT,TYPE = INVOICE上没有任何数据,SALESREF = 5001& FLOW = H“,它会像这样下垂: -
| PO_NO | TYPE | MOVEMENT_TYPE | QUANTITY | SALESREF | FLOW |
|---------- |----------- |--------------- |---------- |---------- |------ |
| 10001001 | G.RECEIPT | 122 | 1000.00 | 5001 | H |
我该怎么做?
已更新
这是我当前的查询
SELECT * FROM dbo.INVOICE
WHERE MVT_TYPE = '122' and TYPE NOT IN ( SELECT TYPE FROM DBO.PO where flow ='H' )
答案 0 :(得分:2)
使用NOT EXISTS:
SELECT *
FROM dbo.INVOICE
WHERE SALESREF = 5001 AND FLOW = 'H' AND NOT EXISTS (SELECT 1
FROM dbo.INVOICE
WHERE SALESREF = 5001 AND FLOW = 'H' AND TYPE = 'INVOICE')
所有SALESREF:
SELECT *
FROM dbo.INVOICE i
WHERE FLOW = 'H' AND NOT EXISTS (SELECT 1
FROM dbo.INVOICE
WHERE FLOW = 'H' AND TYPE = 'INVOICE' AND SALESREF = i.SALESREF)
答案 1 :(得分:0)
您可以使用相关的NOT EXISTS:
SELECT * FROM dbo.INVOICE i
WHERE type='G.RECEIPT'
AND NOT EXISTS(
SELECT * FROM dbo.INVOICE i2
WHERE type='INVOICE'
AND i.PO_NO=i2.PO_NO
AND i.QUANTITY=i2.QUANTITY
AND i.SALESREF=i2.SALESREF
AND i.FLOW=i2.FLOW
)
这样可以更一般地处理需求,因此它可以获得所有不具有匹配INVOICE的G.RECEIPT,而无需对SALESREF或任何其他列进行硬编码。