Home Forums SQL Server 2008 T-SQL (SS2K8) Need help with a script to identify count of negative and positive numbers in a record RE: Need help with a script to identify count of negative and positive numbers in a record

  • Eugene Elutin (11/19/2012)


    Michael Valentine Jones (11/19/2012)


    This should work also:

    select

    abs(sign(col1)+sign(col2)+sign(col3)+

    sign(col4)+sign(col5)) as NegativeCount

    sign(col1)+sign(col2)+sign(col3)+

    sign(col4)+sign(col5)+5 as PositiveCount

    from

    MyTable

    Have you tested it? You should try:

    CREATE TABLE [dbo].[MyTable](

    [col1] [int] NOT NULL,

    [col2] [int] NOT NULL,

    [col3] [int] NOT NULL,

    [col4] [int] NOT NULL,

    [col5] [int] NOT NULL

    ) ON [PRIMARY]

    insert MyTable

    select 0,-0,0,0,0

    union select -3,5,-15,6,0

    union select -3,5,-15,6,-16

    union select 10,-14,8,17,-16

    union select -11,-10,5,2,-4

    union select -6,-2,7,-13,8

    union select -4,2,-6,7,19

    union select -10,8,7,16,-14

    union select 17,-17,-9,14,18

    union select 7,19,15,12,-13

    union select 7,19,15,12,-13

    It's not so simple as appears at first glance, so check my version...;-)

    I think you meant to use "union all select" so that the last entry (a duplicate) is retained.

    Your next solution gets a +1!


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St