我正在尝试计算表格中数据的汇总视图,在查询工作的那一刻,但由于我的表最终将持有10,000+合约,因此效率不高。我还需要按相同的日期过滤每个,我意识到我可以在每个计数的where语句中执行此操作,但这不是非常有效。
如果我可以操作字段而不是选择,那么最后的最终计算会更容易。
(SELECT COUNT (*) FROM Contracts WHERE contractWon = 1) Won,
(SELECT COUNT (*) FROM Contracts WHERE contractPassedToCS = 1) PassedtoCS,
(SELECT COUNT (*) FROM Contracts WHERE contractPassedToCS = 0) as OutstandingWithSales,
(SELECT COUNT (*) FROM Contracts WHERE contractIssued = 1) as ContractsIssued,
(SELECT COUNT (*) FROM Contracts WHERE contractReturned = 1) as ContractsReturned,
(CONVERT(decimal, (SELECT COUNT (*) FROM Contracts WHERE contractReturned = 1)) / CONVERT(decimal, (SELECT COUNT (*) FROM Contracts WHERE contractIssued = 1))) * 100 as '% Outstanding'
我知道可能需要加入,但我有点困惑。
感谢。
答案 0 :(得分:4)
SELECT
SUM(contractWon) AS Won,
SUM(contractPassedToCS ) AS PassedtoCS,
SUM(1-contractPassedToCS) AS OutstandingWithSales,
SUM(contractIssued) AS contractIssued ,
SUM(contractReturned) AS contractReturned,
100.0 * SUM(contractReturned) / SUM(contractIssued) AS '% Outstanding'
FROM
Mytable
“bit”数据类型的备用公式,无法汇总。如果列是int,比如说,那么上面的查询就可以了
--Either CAST first to a type that aggregates...
SUM(CAST(contractWon AS int)) AS Won,
-- .. or rely on COUNT ignores NULL values
COUNT(CASE contractWon WHEN 1 THEN 1 ELSE NULL END) AS Won,