如何获取列名称

时间:2012-10-14 06:29:09

标签: sql sql-server sql-server-2000

使用SQL Server 2000

我想得到位为0的列名和列数,

表1

列名状态(位)

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

我在table1中有超过50行,我想得到列名并计算位为0的位数

预期产出

apple  
graph 
...
...

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

如何查询上述条件

需要查询帮助

1 个答案:

答案 0 :(得分:3)

解决方案

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

输出

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