我使用sql server 2008并连接了多个列来生成值。但是,我想通过所有唯一交易来汇总平均交易成本。
Concatenated values =
SELECT TOP 10 RTRIM(RTRIM(CAST(CENTER_NBR AS CHAR)) + CAST(DATEDIFF(ss, '19700101', SALES_DATE) AS CHAR(10)) +
RTRIM(CAST(REGISTER_NBR AS CHAR)) + RTRIM(CAST(TRANSACTION_NBR AS CHAR)) + CAST(BUSINESS_ENTITY AS CHAR)) AS 'TRANS_KEY'
FROM dh_Transaction_Items;
需要找到以下内容:
ROUND(AVG(CAST(ITEM_QTY AS FLOAT)), 3) AS 'AVG ITEM QTY',
ROUND(AVG(CAST(EXTENDED_PURCHASE_AMT AS FLOAT)), 3) AS 'AVG PURCHASE AMT',
ROUND(AVG(CAST(EXTENDED_SAVINGS_AMT AS FLOAT)), 3) AS 'AVG SAVINGS AMT',
ROUND(AVG(CAST(EXTENDED_COST_AMT AS FLOAT)), 3) AS 'AVG COST AMT',
ROUND(AVG(CAST(EXTENDED_MARGIN_AMT AS FLOAT)), 3) AS 'AVG MARGIN AMT'
基本上,我如何集成两组sql代码来获得平均值。
编辑:
我想找到整个表中五列的平均值(超过100万行)。连接一些列的原因是因为这是“所希望的”。唯一标识符是。因此,AVG应为每个“TRANS_KEY”添加购买金额。并除以总值(超过100万)。
答案 0 :(得分:0)
您需要GROUP BY
子句才能获得每组聚合
SELECT
RTRIM(RTRIM(CAST(CENTER_NBR AS CHAR)) + CAST(DATEDIFF(ss, '19700101', SALES_DATE) AS CHAR(10)) +
RTRIM(CAST(REGISTER_NBR AS CHAR)) + RTRIM(CAST(TRANSACTION_NBR AS CHAR)) + CAST(BUSINESS_ENTITY AS CHAR)) AS 'TRANS_KEY'
,ROUND(AVG(CAST(ITEM_QTY AS FLOAT)), 3) AS 'AVG ITEM QTY',
,ROUND(AVG(CAST(EXTENDED_PURCHASE_AMT AS FLOAT)), 3) AS 'AVG PURCHASE AMT',
,ROUND(AVG(CAST(EXTENDED_SAVINGS_AMT AS FLOAT)), 3) AS 'AVG SAVINGS AMT',
,ROUND(AVG(CAST(EXTENDED_COST_AMT AS FLOAT)), 3) AS 'AVG COST AMT',
,ROUND(AVG(CAST(EXTENDED_MARGIN_AMT AS FLOAT)), 3) AS 'AVG MARGIN AMT'
FROM dh_Transaction_Items
GROUP BY CENTER_NBR, SALES_DATE, REGISTER_NBR, TRANSACTION_NBR, BUSINESS_ENTITY;
答案 1 :(得分:0)
您可以先选择不同的交易,然后通过将qty / amt的总和除以唯一交易的数量来计算平均值,如下所示:
WITH distinct_transactions AS
(
SELECT
DISTINCT
RTRIM(RTRIM(CAST(CENTER_NBR AS CHAR)) + CAST(DATEDIFF(ss, '19700101', SALES_DATE) AS CHAR(10)) +
RTRIM(CAST(REGISTER_NBR AS CHAR)) + RTRIM(CAST(TRANSACTION_NBR AS CHAR)) + CAST(BUSINESS_ENTITY AS CHAR)) AS TRANS_KEY
CAST(ITEM_QTY AS FLOAT) AS ITEM QTY,
CAST(EXTENDED_PURCHASE_AMT AS FLOAT) AS PURCHASE AMT,
CAST(EXTENDED_SAVINGS_AMT AS FLOAT) AS SAVINGS AMT,
CAST(EXTENDED_COST_AMT AS FLOAT) AS COST AMT,
CAST(EXTENDED_MARGIN_AMT AS FLOAT) AS MARGIN AMT
FROM dh_Transaction_Items
)
SELECT
ROUND((SUM(ITEM_QTY) / COUNT(TRANS_KEY)), 3) AS AVG_ITEM_QTY,
ROUND((SUM(PURCHASE_AMT) / COUNT(TRANS_KEY)), 3) AS AVG_PURCHASE AMT,
ROUND((SUM(SAVINGS_AMT) / COUNT(TRANS_KEY)), 3) AS AVG_SAVINGS AMT,
ROUND((SUM(COST_AMT) / COUNT(TRANS_KEY)), 3) AS AVG_COST AMT,
ROUND((SUM(MARGIN_AMT) / COUNT(TRANS_KEY)), 3) AS AVG_MARGIN AMT
FROM distinct_transactions;