聚合函数最小/最大奇怪输出

时间:2011-06-29 12:36:22

标签: sql-server

我有以下代码显示奇怪的输出, 我以前认为当给定组中只有一条记录时,MIN / MAX应该显示相同的结果。 对于MAX,MINTH_2和MONTH_4的结果为0,MIN为2.5,可以理解这种行为的澄清

CREATE TABLE #CUST_ITEM (CUSTNMBR CHAR(31),ITEM CHAR(20),[MONTH] TINYINT,TOT_QTY DECIMAL(10,2))
INSERT INTO #CUST_ITEM VALUES('BA000057','BKNGPDR100',2,200)
INSERT INTO #CUST_ITEM VALUES('BA000057','BKNGPDR100',4,5000)
--QUERY_1 WITH AGGREGATE MIN
SELECT  CUSTNMBR,ITEM, 
MIN(CASE WHEN [MONTH] =2 THEN TOT_QTY ELSE 0 END) AS MONTH_2,
MIN(CASE WHEN [MONTH] =4 THEN TOT_QTY ELSE 0 END) AS MONTH_4,
MIN(CASE WHEN [MONTH] =5 THEN TOT_QTY ELSE 0 END) AS MONTH_5,
SUM(TOT_QTY) AS TOT_QTY_YEAR
FROM 
#CUST_ITEM
GROUP BY CUSTNMBR,ITEM
--QUERY_2 WITH AGGREGATE MAX
SELECT  CUSTNMBR,ITEM, 
MAX(CASE WHEN [MONTH] =2 THEN TOT_QTY ELSE 0 END) AS MONTH_2,
MAX(CASE WHEN [MONTH] =4 THEN TOT_QTY ELSE 0 END) AS MONTH_4,
MAX(CASE WHEN [MONTH] =5 THEN TOT_QTY ELSE 0 END) AS MONTH_5,
SUM(TOT_QTY) AS TOT_QTY_YEAR
FROM 
#CUST_ITEM
GROUP BY CUSTNMBR,ITEM

DROP TABLE #CUST_ITEM

提前致谢

2 个答案:

答案 0 :(得分:1)

嗯,0< 2,5,所以...

您似乎想要执行数据透视查询。这不是将0放在你不想要的行中,而是null!

SELECT  CUSTNMBR,ITEM, 
MIN(CASE WHEN [MONTH] =2 THEN TOT_QTY ELSE null END) AS MONTH_2,
MIN(CASE WHEN [MONTH] =4 THEN TOT_QTY ELSE null END) AS MONTH_4,
MIN(CASE WHEN [MONTH] =5 THEN TOT_QTY ELSE null END) AS MONTH_5,
SUM(TOT_QTY) AS TOT_QTY_YEAR
FROM 
#CUST_ITEM
GROUP BY CUSTNMBR,ITEM

在这种情况下,min或max将避免使用null值来进行聚合,而如果你输入0,则min或max函数将采用该值!

答案 1 :(得分:1)

这是你的个案陈述。

写作时

MIN(CASE WHEN [MONTH] =2 THEN TOT_QTY ELSE 0 END) AS MONTH_2,

MINIMUM值为0或者tot_qty,除非tot_qty是负数,否则为0。

使用NULL代替0,例如:

SELECT  CUSTNMBR,ITEM, 
MIN(CASE WHEN [MONTH] =2 THEN TOT_QTY ELSE NULL END) AS MONTH_2,
MIN(CASE WHEN [MONTH] =4 THEN TOT_QTY ELSE NULL END) AS MONTH_4,
MIN(CASE WHEN [MONTH] =5 THEN TOT_QTY ELSE NULL END) AS MONTH_5,
SUM(TOT_QTY) AS TOT_QTY_YEAR
FROM 
#CUST_ITEM
GROUP BY CUSTNMBR, ITEM
对于我认为你想要的聚合函数,

NULL被忽略。