我在SQL Server 2005中有一个表sales和列ID,paymentType,price的表。

create table sales(id int IDENTITY(1,1),
                   paymentType varchar(2),
                   price decimal(10,2) default(0)
                  )


有一种方法可以在一个查询中执行此操作吗?

SELECT SUM(price) as TE
FROM sales
WHERE paymentType = 'E'

SELECT SUM(price) as TC
FROM sales
WHERE paymentType = 'C'

最佳答案

您可以使用SUM()CASE()实现所需的功能。

SELECT  SUM(CASE WHEN paymentType = 'E' THEN price ELSE 0 END) TE,
        SUM(CASE WHEN paymentType = 'C' THEN price ELSE 0 END) TC
FROM    TableName
WHERE   paymentType IN ('E','C')


需要WHERE来过滤特定的付款,而不是扫描整个表格。您还需要在列paymentType上添加索引以进一步提高性能。

关于sql - 如何优化此查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15812674/

10-12 20:31