使用 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)
如何查询上述条件
需要查询帮助
使用 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)
如何查询上述条件
需要查询帮助
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