想知道其他人将如何实现这一目标或最佳实践。我想在下面两个select语句之间总结SalesTotal和Transaction列,同时将第一个select语句中的值与其他所有语句相连;包括那些未包含在第二个select语句中的列到原始值。
我想避免使用游标或多条件逻辑。理想情况下,如果它可以在单个SQL语句中完成,那么它是首选还是不是?
SELECT Merchant, Department, SUM(SalesTotal) As 'SalesTotal', SUM(Transactions) As 'Transactions', FeeRate, SUM(Gross) As 'Gross', ((SUM(ItemA) * (1 - Rate)) * RateTwo) As 'Rate'
FROM Receipts a
Where TransStatus = 1
Group By Merchant, Department, FeeRate, Rate, RateTwo
和
SELECT Merchant, Department, SUM(SalesTotal) As 'SalesTotal', SUM(Transactions) As 'Transactions'
FROM Receipts a
Where TransStatus = 2
Group By Merchant, Department
答案 0 :(得分:0)
SELECT (CASE WHEN TransStatus = 1 THEN Merchant ELSE 0 END) as 'Merchant' ,
(CASE WHEN TransStatus = 1 THEN Department ELSE 0 END) as 'Department',
(CASE WHEN TransStatus = 1 THEN FeeRate ELSE 0 END) as 'FeeRate' ,
SUM(CASE WHEN TransStatus = 1 THEN Gross ELSE 0 END) As 'Gross',
((SUM(CASE WHEN TransStatus = 1 THEN ItemA ELSE 0 END) * (1 - Rate)) * RateTwo) As 'Rate'
SUM(SalesTotal) As 'SalesTotal',
SUM(Transactions) As 'Transactions'
FROM Receipts
Group By Merchant, Department,
CASE WHEN TransStatus = 1 THEN FeeRate END,
CASE WHEN TransStatus = 1 THEN Rate END,
CASE WHEN TransStatus = 1 THEN RateTwo END