这是我的代码:
SELECT CASHIER_ID AS SERVER, CONVERT(VARCHAR(10),[DATETIME],111) AS DATE,
SUM(GRAND_TOTAL) AS TOTAL_SALES,
SUM(NUM_PEOPLE_PARTY) AS NUMBER_SERVED,
SUM(GRAND_TOTAL) / SUM(NUM_PEOPLE_PARTY) AS CASHPERCUSTOMER
FROM INVOICE_TOTALS
WHERE [DATETIME] >= '2012-06-01'
GROUP BY CASHIER_ID, CONVERT(VARCHAR(10),[DATETIME],111)
除了:
之外,一切都与代码完美配合SUM(GRAND_TOTAL) / SUM(NUM_PEOPLE_PARTY) AS CASHPERCUSTOMER
部。如果我把这条线拿出去,那么一切都很完美,如果我把它放入,我会收到以下错误:
消息:无法检索数据表。
SELECT CASHIER_ID AS SERVER,...上面的其余查询...
堆栈跟踪:
......不相关的堆栈跟踪......消息:遇到零除错误。
堆栈跟踪:
...不相关的堆栈跟踪...
这是使用SQL Server的餐厅销售点(POS)系统内的SQL。有什么想法可能会发生吗?
答案 0 :(得分:4)
您需要以这种方式运行查询,并告诉我们是否有任何结果:
SELECT CASHIER_ID AS SERVER,
CONVERT(VARCHAR(10),[DATETIME],111) AS DATE,
SUM(GRAND_TOTAL) AS TOTAL_SALES,
SUM(NUM_PEOPLE_PARTY) AS NUMBER_SERVED
FROM INVOICE_TOTALS
WHERE [DATETIME] >= '2012-06-01'
GROUP BY CASHIER_ID, CONVERT(VARCHAR(10),[DATETIME],111)
HAVING SUM(NUM_PEOPLE_PARTY) = 0;
如果有结果,那么显然您的查询需要满足它们。例如:
SELECT SERVER, [DATE], TOTAL_SALES, NUMBER_SERVED,
CASHPERCUSTOMER = TOTAL_SALES / NULLIF(NUMBER_SERVED, 0)
FROM
(
SELECT CASHIER_ID AS SERVER,
CONVERT(VARCHAR(10),[DATETIME],111) AS DATE,
SUM(GRAND_TOTAL) AS TOTAL_SALES,
SUM(NUM_PEOPLE_PARTY) AS NUMBER_SERVED
FROM INVOICE_TOTALS
WHERE [DATETIME] >= '2012-06-01'
GROUP BY CASHIER_ID, CONVERT(VARCHAR(10),[DATETIME],111)
);
但你应该弄清楚为什么有0的结果,因为这没有多大意义。
答案 1 :(得分:3)
分开前检查0:
SELECT
...,
CASE WHEN SUM(NUM_PEOPLE_PARTY) = 0
THEN NULL
ELSE SUM(GRAND_TOTAL) / SUM(NUM_PEOPLE_PARTY) END AS CASHPERCUSTOMER,
...
使用NULLIF
获得相同的结果:
SELECT
...,
CASE SUM(GRAND_TOTAL) / NULLIF(SUM(NUM_PEOPLE_PARTY), 0) AS CASHPERCUSTOMER,
...