0

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)

上記条件のクエリの作成方法

クエリのヘルプが必要

4

1 に答える 1

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
于 2012-10-14T07:30:30.907 に答える