如何修改Count(*)结果

时间:2019-02-15 13:52:03

标签: sql sql-server tsql

需要修改计数结果。

输入查询:

SELECT COUNT(*) COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = '<**TableName**>' 
 AND COLUMN_NAME IN ('**Column1Name**','**Column2Name**')

输出: 2

我的要求是,如果表中同时存在两列enter image description here,则结果应为'1'。

有人可以通过简单的解决方案帮助我吗?

3 个答案:

答案 0 :(得分:0)

您可以进行聚合:

SELECT 1 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = '<**TableName**>' AND 
      COLUMN_NAME IN ('**Column1Name**','**Column2Name**')
GROUP BY TABLE_NAME
HAVING COUNT(*) = 2;

您必须确保HAVING COUNT(*) = 2的计数值与IN子句参数定义的计数值完全相同。

例如:

如果为COLUMN_NAME IN ('**Column1Name**','**Column2Name**', '**Column3Name**'),则HAVING子句为HAVING COUNT(*) = 3

答案 1 :(得分:0)

您缺少Have子句。

SELECT 1 COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = '<**TableName**>' 
 AND COLUMN_NAME IN ('**Column1Name**','**Column2Name**') having count(*)=2

SELECT case when count(*)=2 then 1 else 0 end COLUMN_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = '<**TableName**>' 
     AND COLUMN_NAME IN ('**Column1Name**','**Column2Name**') having count(*)=2

答案 2 :(得分:0)

如果您想使用10,则可以使用case

SELECT (CASE WHEN COUNT(*) = 2 THEN 1 ELSE 0 END)
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = '<**TableName**>' AND
      COLUMN_NAME IN ('**Column1Name**','**Column2Name**');