我在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'
答案 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
上添加索引以提高性能。