选择迭代第一个查询结果的查询

时间:2015-02-16 16:29:18

标签: sql sql-server

这是我们目前的代码,它可以作为选择查询正常工作:

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)。

我们想要做的是在表中获取列表中不同MAIN引用的值,然后让它遍历上面的代码,为每个MAIN引用生成一行。我们不太确定如何在SQL中表达这一点。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

可能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' 

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

答案 1 :(得分:0)

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' 

答案 2 :(得分:0)

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

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