我试图计算表中每一列的不同值。
我想通过使用一个临时表来做到这一点,该表具有我想要计数的每个列名。然后,通过使用作为该表索引的变量,我想将不同的计数插入到第二个临时表中。
CREATE TABLE ##test ([row] [int] NOT NULL, [COLUMN_NAME] [char] (100))
Insert INTO ##test ([row], [COLUMN_NAME])
VALUES
(1,'[Equipment Number]'),
(2,'[CEID]'),
(3,'[Serial Number]'),
(4,'[Manufacturer]')
CREATE TABLE ##test2 ([COLUMN_NAME] [char] (100), [Dist Count][INT])
DECLARE @i INT = 1
DECLARE @COL [char] (100)
WHILE @i <= 4 --i.e. the number of rows in ##test
BEGIN
SET @COL = (select [COLUMN_NAME] from ##test WHERE [row] = @i)
Insert INTO ##test2 Values (@COL, (SELECT count(DISTINCT @COL) FROM [Database].[Original_Table]))
SET @i = @i+1
END
我期望在## test2中的输出如下:
COLUMN_NAME |Dist Count
[Equipment Number]|1,234
[CEID] |456
[Serial Number] |789
[Manufacturer] |1,011
但是在表中,我得到的表的Dist Count中全为1
COLUMN_NAME |Dist Count
[Equipment Number]|1
[CEID] |1
[Serial Number] |1
[Manufacturer] |1
如何让我的第二个循环识别@COL是Original_Table中的列名?