如何在使用2个表和GROUP BY语法时从1个表中选择数据?

时间:2011-05-25 15:15:28

标签: sql-server

我在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

中的一个字段

2 个答案:

答案 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 ) 

使用Common table expression

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