Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 SQL Formula Help

Author  Topic 

Omprakash
Starting Member

4 Posts

Posted - 2013-10-17 : 04:37:44
Hi,

I have the below result from a table. Basically an invoice number can have multiple lines. if any invoice line has a value 'N' under Approved column, i would like to add a new Check column that shows 'N' in all the lines.

Invoice_No Line_No Approved Check
123 1 Y N
123 2 Y N
123 3 N N
73 1 Y Y
73 2 Y Y


Can someone help me with the formula to get the above result?

Thanks,
Om

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-10-17 : 04:56:25
[code]
SELECT *,
CASE WHEN SUM(CASE WHEN Approved = 'N' THEN 1 ELSE 0 END) OVER (PARTITION BY Invoice_No) > 0 THEN 'N' ELSE 'Y' END AS Check
FROM table
[/code]

If you want value to be added to table then you need this

[code]
ALTER TABLE TableName ADD Check char(1) NOT NULL DEFAULT 'Y'

UPDATE t
SET Check = 'N'
FROM (SELECT check,
SUM(CASE WHEN Approved = 'N' THEN 1 ELSE 0 END) OVER (PARTITION BY Invoice_No) AS InvoiceChkCnt
FROM TableName
)t
WHERE InvoiceChkCnt > 0
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -