How to merge rows of SQL data on column-based logic?

夙愿已清 提交于 2019-12-24 17:14:00

问题


I'm writing a margin report on our General Ledger and I've got the basics working, but I need to merge the rows based on specific logic and I don't know how...

My data looks like this:

value1      value2      location  date          category                     debitamount    creditamount
2029        390         ACT       2012-07-29    COSTS - Widgets and Gadgets  0.000          3.385
3029        390         ACT       2012-07-24    SALES - Widgets and Gadgets  1.170          0.000

And my report needs to display the two columns together like so:

plant   date          category               debitamount    creditamount
ACT     2012-07-29    Widgets and Gadgets    1.170          3.385

The logic to join them is contained in the value1 and value 2 column. Where the last 3 digits of value 1 and all three digits of value 2 are the same, the rows should be combined. Also, the 1st digit of value 1 will always been 2 for sales and 3 for costs (not sure if that matters)

IE 2029-390 is money coming in for Widgets and Gadgets sold to customers, while 3029-390 is money being spent to buy the Widgets and Gadgets from suppliers.

How can I so this programmatically in my stored procedure? (SQL Server 2008 R2)

Edit: Would I load the 3000's into one variable table the and the 2000's into another, then join the two on value2 and right(value1, 3)? Or something like that?


回答1:


Try this:

SELECT RIGHT(LTRIM(RTRIM(value1)),3) , value2, MAX(location), MAX(date), MAX(category), SUM(debitamount), SUM(creditamount) FROM table1 GROUP BY RIGHT(LTRIM(RTRIM(value1)),3), value2

It will sum the credit amount and debit amount. It will choose the maximum string value in the other columns, assuming they are always the same when value2 and the last 3 digits of value1 are the same it shouldn't matter.



来源:https://stackoverflow.com/questions/8979911/how-to-merge-rows-of-sql-data-on-column-based-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!