Search code examples
sqlsql-serversql-server-2000

How to get the column name


Using SQL Server 2000

I want to get the column name and column count where bit is 0,

table1

columnname status(bit)

apple  0
orange 1
graph 0
pine 1
....

I have more than 50 rows in table1, I want to get the columnname and count where bit is 0

Expected Output

apple  
graph 
...
...

Count - 22 (total column count where bit is 0)

How to make a query for the above condition

Need Query Help


Solution

  • Solutions

    DECLARE @MyTable TABLE (
        ColumnName VARCHAR(50) NOT NULL,
        Status BIT NOT NULL
    );
    
    INSERT  @MyTable (ColumnName, Status)
    SELECT 'apple', 0
    UNION ALL SELECT 'orange', 1
    UNION ALL SELECT 'graph', 0
    UNION ALL SELECT 'pine', 1;
    
    Print 'Solution 0 ... (no grouping, 2 resultsets)'
    SELECT  t.ColumnName
    FROM    @MyTable t
    WHERE   t.Status=0
    SELECT  @@ROWCOUNT AS cnt
    
    Print 'Solution 1 ... (group by ColumnName, 2 resultsets)'
    SELECT  t.ColumnName
    FROM    @MyTable t
    WHERE   t.Status=0
    ORDER BY t.ColumnName
    COMPUTE COUNT(t.ColumnName)
    
    Print 'Solution 2 ... (1 resultset, 2 columns)'
    SELECT  t.ColumnName, COUNT(*)
    FROM    @MyTable t
    WHERE   t.Status=0
    GROUP BY t.ColumnName WITH ROLLUP
    
    Print 'Solution 3 ... (1 resultset, 1 column, last row contains the cnt value)'
    SELECT  CASE WHEN x.IsGrouping=0 THEN x.ColumnName ELSE CONVERT(VARCHAR(11),x.Cnt) END AS CocoJambo
    FROM (
        SELECT  t.ColumnName, 
                COUNT(*) AS Cnt,
                GROUPING(t.ColumnName) AS IsGrouping
        FROM    @MyTable t
        WHERE   t.Status=0
        GROUP BY t.ColumnName WITH ROLLUP
    ) x
    ORDER BY x.IsGrouping
    

    Output

    Solution 0 ... (no grouping, 2 resultsets)
    ColumnName
    ----------
    apple
    graph
    
    cnt
    ---
    2
    
    Solution 1 ... (group by ColumnName, 2 resultsets)
    ColumnName
    ----------
    apple
    graph
    
    cnt
    ---
    2
    
    Solution 2 ... (1 resultset, 2 columns)
    ColumnName 
    ---------- -
    apple      1
    graph      1
    NULL       2
    
    Solution 3 ... (1 resultset, 1 column, last row contains the cnt value)
    CocoJambo
    ---------
    apple
    graph
    2