Custom SQL GROUP BY Clause

给你一囗甜甜゛ 提交于 2020-02-03 10:25:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!