0

我是 SQL 新手,我使用的是 SQL Server 2008。

在我的数据库中,我有 3 个表

  1. 桌子Type
  2. 桌子Invoice
  3. 桌子Item

这是我获取总金额的 SQL 命令:

SELECT 
   tbl_type.type,
   ((tbl_item.price * qty) - (tbl_item.price * qty * discount)) as totalAfter,
   tbl_inv.dateInv
FROM 
   tbl_type, tbl_item, tbl_inv 
WHERE 
   tbl_inv.dateInv = '2013-03-26 00:00:00' 
   AND tbl_inv.id = tbl_item.id_invoice 
   AND tbl_type.id = tbl_item.id_type
ORDER BY 
   tbl_inv.dateInv;

所以当我运行我的查询时,它会返回

CHICKEN        46.000000    2013-03-26 00:00:00.000
MEAT            3.000000    2013-03-26 00:00:00.000
CHICKEN        69.000000    2013-03-26 00:00:00.000
CHICKEN        46.000000    2013-03-26 00:00:00.000
CHICKEN        69.000000    2013-03-26 00:00:00.000
MEAT            4.500000    2013-03-26 00:00:00.000

但是如何做到这一点呢?

CHICKEN       230.000000    2013-03-26 00:00:00.000
MEAT            7.500000    2013-03-26 00:00:00.000

我会收到错误

列 'tbl_item.price' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

当我GROUP BY tbl_type.type在我的 SQL 中使用时

感谢帮助。

4

1 回答 1

3
SELECT tbl_type.type,SUM((tbl_item.price * qty) - (tbl_item.price * qty * discount)) as totalAfter ,tbl_inv.dateInv
FROM tbl_type,tbl_item,tbl_inv 
WHERE tbl_inv.dateInv = '2013-03-26 00:00:00' AND tbl_inv.id=tbl_item.id_invoice AND tbl_type.id=tbl_item.id_type
Group by tbl_type.type,tbl_inv.dateInv
ORDER BY tbl_inv.dateInv,tbl_type.type;
于 2013-04-18T11:13:55.207 回答