我有以下SQL,我试图获得总计数超过一个月的每日平均值。
var result = selectInfo.SelectInfoByName("info").Result;
随着上面的数据运行,我得到36行(我的计数)的输出,我将其除以31(天),并且预计每日平均值为1.161,但是我的每行平均输出为.032258(我已经确定是1.16 / 36)。非聚合列位于Group By中,但是以某种方式偏离了每日平均值。
如果我只按计算的平均值SELECT A.BUSINESS_UNIT, A.INV_ITEM_ID, C.MFG_ID, C.MFG_ITM_ID,
A.ADJUST_TYPE, A.QTY_BASE, A.UNIT_MEASURE_STD,
A.DT_TIMESTAMP, B.DESCR254_MIXED, A.TRANSACTION_GROUP,
(CONVERT(CHAR(10),A.TRANSACTION_DATE,121)), A.DEPTID, B.PRICE_LIST,
A.DESTIN_GL_BU, A.QTY_BASE* B.PRICE_LIST, (COUNT(*) * 1.0 / 31 ) AS 'Daily
Average'
FROM PS_TRANSACTION_INV A, (PS_PURCH_ITEM_ATTR B LEFT OUTER JOIN
PS_ITEM_MFG C ON B.SETID = C.SETID AND B.INV_ITEM_ID = C.INV_ITEM_ID ),
PS_CM_ACCTG_DIST_D D
WHERE ( A.BUSINESS_UNIT = '11MMS'
AND A.INV_ITEM_ID = B.INV_ITEM_ID
AND C.PREFERRED_MFG = 'Y'
AND A.TRANSACTION_DATE >= '05-01-2018'
AND A.TRANSACTION_DATE <= '05-31-2018'
AND A.BUSINESS_UNIT = D.BUSINESS_UNIT
AND A.INV_ITEM_ID = D.INV_ITEM_ID
AND D.TRANSACTION_GROUP = A.TRANSACTION_GROUP
AND A.INV_ITEM_ID = '1')
GROUP BY A.BUSINESS_UNIT, A.INV_ITEM_ID, C.MFG_ID, C.MFG_ITM_ID,
A.ADJUST_TYPE, A.QTY_BASE, A.UNIT_MEASURE_STD,
A.DT_TIMESTAMP, B.DESCR254_MIXED, A.TRANSACTION_GROUP,
(CONVERT(CHAR(10),A.TRANSACTION_DATE,121)), A.DEPTID, B.PRICE_LIST,
A.DESTIN_GL_BU, A.QTY_BASE* B.PRICE_LIST
运行查询,那么我得到正确的每日平均值1.161,所以我知道它与Group By有关。提前谢谢!
修改
运行此查询
(COUNT(*) * 1.0 / 31 ) AS 'Daily Average'
产生1.161的正确结果,就在我将其添加到上面的查询中时,我的结果不正确。这就是我想在主查询中模仿的内容。
答案 0 :(得分:1)
当您按所有列添加分组时,count将始终为1,从而得到结果。
最简单的方法就是将第二个查询作为子查询添加到主查询中,然后就可以丢失该组,如下所示:
SELECT A.BUSINESS_UNIT, A.INV_ITEM_ID, C.MFG_ID, C.MFG_ITM_ID,
A.ADJUST_TYPE, A.QTY_BASE, A.UNIT_MEASURE_STD,
A.DT_TIMESTAMP, B.DESCR254_MIXED, A.TRANSACTION_GROUP,
(CONVERT(CHAR(10),A.TRANSACTION_DATE,121)), A.DEPTID, B.PRICE_LIST,
A.DESTIN_GL_BU, A.QTY_BASE* B.PRICE_LIST,
(SELECT COUNT(*) * 1.0 / 31
FROM PS_TRANSACTION_INV A, (PS_PURCH_ITEM_ATTR B LEFT OUTER JOIN
PS_ITEM_MFG C ON B.SETID = C.SETID AND B.INV_ITEM_ID = C.INV_ITEM_ID ),
PS_CM_ACCTG_DIST_D D
WHERE ( A.BUSINESS_UNIT = '11MMS'
AND A.INV_ITEM_ID = B.INV_ITEM_ID
AND C.PREFERRED_MFG = 'Y'
AND A.TRANSACTION_DATE >= '05-01-2018'
AND A.TRANSACTION_DATE <= '05-31-2018'
AND A.BUSINESS_UNIT = D.BUSINESS_UNIT
AND A.INV_ITEM_ID = D.INV_ITEM_ID
AND D.TRANSACTION_GROUP = A.TRANSACTION_GROUP
AND A.INV_ITEM_ID = '1')
) AS 'Daily Average'
FROM PS_TRANSACTION_INV A, (PS_PURCH_ITEM_ATTR B LEFT OUTER JOIN
PS_ITEM_MFG C ON B.SETID = C.SETID AND B.INV_ITEM_ID = C.INV_ITEM_ID ),
PS_CM_ACCTG_DIST_D D
WHERE ( A.BUSINESS_UNIT = '11MMS'
AND A.INV_ITEM_ID = B.INV_ITEM_ID
AND C.PREFERRED_MFG = 'Y'
AND A.TRANSACTION_DATE >= '05-01-2018'
AND A.TRANSACTION_DATE <= '05-31-2018'
AND A.BUSINESS_UNIT = D.BUSINESS_UNIT
AND A.INV_ITEM_ID = D.INV_ITEM_ID
AND D.TRANSACTION_GROUP = A.TRANSACTION_GROUP
AND A.INV_ITEM_ID = '1')