我在SQL Server中有两个连接在一起的表。当我想从一个表中应用GROUP BY
语法和SELECT时,它会影响第二个表..
当我使用2个表格和SELECT
语法时,如何从1个表中GROUP BY
数据?
SELECT
tblProduct.fTechnicalNo, tblProduct.fName,
tblProduct.fDesc, tblProduct.fRegisterDate,
SUM(tblOrders.fCount) AS Expr1, tblOrders.fSaleDate
FROM tblProduct
INNER JOIN tblOrders ON tblProduct.fId = tblOrders.fxProductId
WHERE
(tblProduct.fRegisterDate >= @Since)
AND (tblProduct.fRegisterDate <= @To)
GROUP BY
tblProduct.fTechnicalNo, tblProduct.fName,
tblProduct.fDesc, tblProduct.fRegisterDate,
tblOrders.fSaleDate, tblOrders.fCount
我想SELECT
只有tblProduct
个数据。但GROUP BY
语法会更改结果并在结果中显示tblOrders
数据。我只需要tblProduct
结果,只需tblOrders
答案 0 :(得分:0)
在内联视图中使用
SELECT tblproduct.ftechnicalno,
tblproduct.fname,
tblproduct.fdesc,
tblproduct.fregisterdate
FROM tblproduct
INNER JOIN (SELECT SUM(tblorders.fcount) AS sumoffcount,
tblorders.fsaledate,
tblorders.fxproductid tblorders
GROUP BY tblorders.fsaledate,
tblorders.fxproductid) orderdata
ON tblproduct.fid = orderdata.fxproductid
WHERE ( tblproduct.fregisterdate >= @Since )
AND ( tblproduct.fregisterdate <= @To )
With orderdata as
(SELECT SUM(tblorders.fcount) AS sumoffcount,
tblorders.fsaledate,
tblorders.fxproductid tblorders
GROUP BY tblorders.fsaledate,
tblorders.fxproductid)
SELECT tblproduct.ftechnicalno,
tblproduct.fname,
tblproduct.fdesc,
tblproduct.fregisterdate
FROM tblproduct
INNER JOIN orderdata
ON tblproduct.fid = orderdata.fxproductid
WHERE ( tblproduct.fregisterdate >= @Since )
AND ( tblproduct.fregisterdate <= @To )
答案 1 :(得分:0)
你不能通过聚合来做一个小组......你的查询还不错......
SELECT
tblProduct.fTechnicalNo,
tblProduct.fName,
tblProduct.fDesc,
tblProduct.fRegisterDate,
tblOrders.fSaleDate,
SUM(tblOrders.fCount) AS Expr1
FROM
tblProduct
JOIN tblOrders ON tblProduct.fId = tblOrders.fxProductId
WHERE
tblProduct.fRegisterDate >= @Since
AND tblProduct.fRegisterDate <= @To
GROUP BY
tblProduct.fTechnicalNo,
tblProduct.fName,
tblProduct.fDesc,
tblProduct.fRegisterDate,
tblOrders.fSaleDate