问题
I have a very customized SQL query that I am having problems implementing. I am using SQL-Server-2008.
I have only one table in this query, but I am looking for very specific data. The requirements for this query are:
For each DISTINCT PartNumber (column), I need to select the NEWEST (max) PO (column) to be selected. However, there is another column named "Receipt" where if it contains a value at all, then the PartNumber should be excluded all together.
I am somewhat familiar with GROUP BY clauses and CASES for selections, but I'm not sure how to tie all I know together into one working query...
Any help is greatly appreciated! Thanks in advance =).
回答1:
SELECT Partnumber, MAX(PO)
FROM MyTable t1
WHERE NOT EXISTS (SELECT 1
FROM MyTable
WHERE (Receipt <> '0'
OR Receipt <> '')
AND Partnumber = t1.partnumber)
GROUP BY PartNumber
The NOT EXISTS
here will exclude any row that has a partnumber for which a receipt is populated anywhere in the table.
回答2:
Here's the Anti-Join option
SELECT t1.Partnumber, MAX(t1.PO)
FROM MyTable t1
LEFT JOIN
(SELECT DISTINCT PartNumber From MyTable
WHERE COALESCE(Receipt, '') = '') t2
ON t1.Partnumber = t2.Partnumber
WHERE
t2.Partnumber is null
GROUP BY t1.PartNumber
回答3:
SELECT MAX(PO)
FROM aTable
WHERE PartNumber NOT IN (
SELECT PartNumber
FROM aTable
WHERE Receipt IS NULL
GROUP BY PartNumber
HAVING PartNumber IS NOT NULL /* fix */
)
GROUP BY PartNumber
回答4:
Edit: Based on clarification in comments, this simplifies to:
If I understand you correctly, this should do it:
SELECT MAX(PO)
FROM Table
GROUP BY PartNumber
HAVING MAX(Receipt) = 0
The HAVING
clause will eliminate any PartNumber
where there is even a single non-zero Receipt
entry for any rows with that PartNumber
.
来源:https://stackoverflow.com/questions/9023314/custom-sql-group-by-clause