如何优化此查询?

时间:2013-04-04 13:28:10

标签: sql sql-server-2005

我在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'

2 个答案:

答案 0 :(得分:6)

您可以使用GROUP BY按paymentType对值进行分组,并获得两个带有和的“E”和“C”记录

SELECT paymentType,SUM(price) 
FROM sales 
WHERE paymentType = 'E' or paymentType = 'C'
GROUP BY paymentType

答案 1 :(得分:4)

您可以使用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上添加索引以提高性能。