如何根据另一列的值选择某些行值?

时间:2015-06-23 20:49:15

标签: sql sql-server

我尝试搜索这个,但在整个表格上获得了很多过滤器。我正在使用Microsoft SQL Server Management Studio 11.0.2100.60。

我的查询目前返回如下所示的内容。

╔═══════════╦═════════╦════════════════╦═══════╦════════════╗
║  Account  ║ Balance ║    Invoice     ║ Code  ║    Date    ║
╠═══════════╬═════════╬════════════════╬═══════╬════════════╣
║ 500018802 ║ -80.00  ║ 500018802-0002 ║ PBH   ║ 2012-04-05 ║
║ 500018802 ║ -140.00 ║ 500018802-0003 ║ DLPBH ║ 2012-05-05 ║
║ 500018802 ║ -60.00  ║ 500018802-0006 ║ DLPBH ║ 2012-08-05 ║
║ 500018802 ║ -140.00 ║ 500018802-0001 ║ PBH   ║ 2012-03-23 ║
╚═══════════╩═════════╩════════════════╩═══════╩════════════╝

我要做的是将数据分组以获得一个帐号,同时总结余额。但是,由于发票/代码/日期不同,我不能做一个简单的小组。那么有没有办法根据其他列值选择某些行值?理想情况下,我想要的是将代码和日期值设置为发票号具有最小值的行中的任何值,同时总和余额。所以在这种情况下,它是最后一行,我的结果是:

╔═══════════╦═════════╦════════════════╦══════╦════════════╗
║  Account  ║ Balance ║    Invoice     ║ Code ║    Date    ║
╠═══════════╬═════════╬════════════════╬══════╬════════════╣
║ 500018802 ║ -420.00 ║ 500018802-0001 ║ PBH  ║ 2012-03-23 ║
╚═══════════╩═════════╩════════════════╩══════╩════════════╝ 

这只是一个帐户的数据。我的表会有许多行的许多帐户。

编辑*这是我当前的查询。

SELECT Account
    SUM(Balance) AS Balance,
    Invoice,
    Code,
    Date
FROM MyData
GROUP BY Account,   Invoice, Code, Date
ORDER BY Account

2 个答案:

答案 0 :(得分:1)

你可以试试这个

WITH cte AS(
    SELECT 
        Account,
        SUM(Balance) OVER (PARTITION BY Account) Balance,
        Invoice,
        Code,
        [Date],
        ROW_NUMBER() OVER (PARTITION BY Account ORDER BY Invoice) RN
    FROM
        Accounts
)
SELECT * 
FROM cte 
WHERE RN = 1

答案 1 :(得分:0)

以下是一些例子:

with cte1 as(your current query),
cte2 as(select *, 
               row_number() over(partition by account order by invoice) rn,
               sum(balance) over(partition by account) as b
        from cte1)
select * from cte2
where rn = 1