显示列名称以及总和

时间:2017-03-24 04:19:55

标签: sql-server

我只是在SQL Server中做一些练习。我的下面的查询总结了一个数量列,但我也希望用它返回相应的项目编号列和项目描述列。每次我尝试它告诉我item_no列是不明确的。关于这意味着什么,我已经做了一些阅读,但我仍然不清楚。我错过了什么?

declare @startdate int = '20161201'
declare @enddate int = '20170401'



SELECT  sum(qty) as total_units, item_no as item_number from fact_sales 
inner join dim_item 
on fact_sales.item_no=dim_item.item_no
where vendor_id = 'roche' and date_key between @startdate and @enddate 
order by fact_sales.item_no 

1 个答案:

答案 0 :(得分:3)

你遗失了几件事

DECLARE @startdate INT = '20161201'
DECLARE @enddate INT = '20170401'

SELECT sum(fact_sales.qty) AS total_units
    ,dim_item.item_no AS item_number
    ,dim_item.item_discription
FROM fact_sales
INNER JOIN dim_item ON fact_sales.item_no = dim_item.item_no
WHERE vendor_id = 'roche'
    AND date_key BETWEEN @startdate
        AND @enddate

GROUP BY dim_item.item_no,dim_item.item_discription
ORDER BY fact_sales.item_no
  1. 分组依据
  2. 使用表名/表别名
  3. 添加列名称