如何计算两个独立行的同一列的商?

时间:2014-09-24 07:51:17

标签: sql sql-server

我有下表test

MonthNumber    Fees      FeesName
1              10        A
2              22        A
3              25        A
1              11        B
2              25        B
3              28        B
3              8         C
3              2         D
3              3         E

对于每个Fees(A) / Fees(B),我正在寻找MonthNumber

2 个答案:

答案 0 :(得分:1)

你的问题非常稀少,但如果我理解你的话,那么你想要这样的事情:

SELECT A.Fees / B.Fees
FROM test A
    INNER JOIN test B ON A.MonthNumber = B.MonthNumber
WHERE A.FeesName = 'A' AND B.FeesName = 'B'

基本上,加入桌子对抗自己并像往常一样运行你的分区。

答案 1 :(得分:1)

使用Pivot:

;WITH CTE AS
(
  SELECT MonthNumber, Fees, Feesname 
  FROM test
  WHERE FeesName in ('A', 'B')
) 
SELECT MonthNumber, [A]/[B]
FROM  cte
PIVOT (SUM(Fees) FOR [Feesname] IN ([A], [B])) AS pvt 
ORDER BY MonthNumber

如果您不喜欢pivot或使用sqlserver 2005或更早版本

SELECT 
  MonthNumber, 
  SUM(CASE WHEN FeesName = 'A' THEN Fees END)/
  SUM(CASE WHEN FeesName = 'B' THEN Fees END) result
FROM test
WHERE FeesName in ('A', 'B')
GROUP BY MonthNumber
ORDER BY MonthNumber