我有两个表格,可以通过name
和dateOfInput
连接自己。
表格文件
id
name
price
dateOfDocument
dateOfInput
表客户
id
identification
name
dateOfInput
我想在网格中显示的数据是这样的:
Name | Identification | Total Price | Total Quantity
John #1 15.31 2
Stack #13 9.90 1
在数据库中,各表的行是:
行文档:
VALUES('John', 10.31, '2015-01-01', '2015-01-01 15:00')
VALUES('John', 5.00, '2015-01-02', '2015-01-02 13:00')
VALUES('Stack', 9.90, '2015-01-01, '2015-01-01 12:00')
行客户:
VALUES('#1', 'John', '2015-01-01 15:00')
VALUES('#1', 'John', '2015-01-02 13:00')
VALUES('#13', 'Stack', '2015-01-01 12:00')
为了完成我想要的网格,这里是我的选择:
SELECT doc.name, cust.identification,
SUM(doc.price) AS `totalPrice`,
COUNT(doc.name) AS `totalQuantity`
FROM documents AS doc
INNER JOIN customers AS cust ON cust.name = doc.name
WHERE doc.dateOfDocument >= '2015-01-01' AND
doc.dateOfInput = cust.dateOfInput
GROUP BY doc.name
我收到的输出在价格和数量上都是错误的。
Name | Identification | Total Price | Total Quantity
John #1 10.31 1
Stack #13 9.90 1
答案 0 :(得分:1)
尝试将cust.identification
添加到GROUP BY
子句
答案 1 :(得分:1)
这给了我正确的结果(注意GROUP BY更改):
SELECT doc.name, cust.identification,
SUM(doc.price) AS 'totalPrice',
COUNT(doc.name) AS 'totalQuantity'
FROM mg_tblDocuments AS doc
INNER JOIN mg_tblCustomers AS cust ON cust.name = doc.name
WHERE doc.dateOfDocument >= '2015-01-01' AND
doc.dateOfInput = cust.dateOfInput
GROUP BY doc.name, cust.identification -- add me
编辑:殴打它:)