Sql 选择遍历第一个查询结果的查询

Sql 选择遍历第一个查询结果的查询,sql,sql-server,Sql,Sql Server,这是我们目前拥有的代码,可以很好地用作select查询: SELECT DISTINCT Reference, (SELECT amount FROM tbl_DDTransactions WHERE DueDate = '2015-01-15' AND Reference = 'MAIN0134') AS LastMonth, (SELECT amount FROM tbl_DDTransactions WHERE DueDate = '20

这是我们目前拥有的代码,可以很好地用作select查询:

SELECT DISTINCT
  Reference,
  (SELECT
    amount
  FROM tbl_DDTransactions
  WHERE DueDate = '2015-01-15'
  AND Reference = 'MAIN0134')
  AS LastMonth,
  (SELECT
    amount
  FROM tbl_DDTransactions
  WHERE DueDate = '2015-02-15'
  AND Reference = 'MAIN0134')
  AS CurrentMonth
FROM tbl_DDTransactions
WHERE Reference = 'MAIN0134'
我们从中提取此信息的表可以有任意数量的条目(每行实际上与公司引用为MAINxxxx的事务相关)


我们要做的是获取一个列表,其中包含表中不同的主引用的值,然后让它在上面的代码中循环,为每个主引用生成一行。不过,我们不太确定如何在SQL中表达这一点。感谢您的帮助。

可能是
pivot
是您需要的

SELECT Reference,
       [2015-01-15] LastMonth,
       [2015-02-15] CurrentMonth
FROM   yourtable
       PIVOT (Max(amount)
             FOR DueDate IN([2015-01-15],
                            [2015-02-15]))piv
WHERE  Reference = 'MAIN0134' 

注意:以上内容可以修改为动态工作

乍一看,这看起来像一个简单的聚合:

select  r.reference,
        a1.amount as lastMonth,
        a2.amount as currentMonth
from    (select distinct reference from tbl_DDTransactions) as r
        left join tbl_DDTransactions a1 on a1.reference = r.reference and a1.DueDate = '2015-01-15' 
        left join tbl_DDTransactions a2 on a2.reference = r.reference and a2.DueDate = '2015-02-15' 
SELECT
  Reference, 
  sum(case when DueDate = '2015-01-15' then amount end) AS LastMonth,
  sum(case when DueDate = '2015-02-15' then amount end) AS CurrentMonth
FROM tbl_DDTransactions
GROUP BY Reference