返回获得行计数并保持没有行的列

时间:2019-01-28 16:45:16

标签: sql-server tsql

如果我运行以下命令:

select [agent_name], [agent_department], count(*) as [row_count]
from [table_name]
where [agent_name] IS NOT NULL
group by [agent_name] [agent_department];

如果没有要返回的记录(即表为空),则什么也不会返回。

如果我运行此

select count(*) as [row_count]
from [table_name]
where [agent_name] IS NOT NULL

我的row_count为0。

有没有一种方法可以运行第一个查询,并且如果没有记录,它是否返回row_count 0?

1 个答案:

答案 0 :(得分:2)

这可能不是很漂亮,但它应该带回您想要的东西:

我从一个小模型开始:

import os
import sys

def delete_py(path, subfolder):
    try:
        if os.path.exists(path):
            for (root, dirs, files) in os.walk(path):
                for dir in dirs:
                    if dir == subfolder:
                        goto = os.path.join(root, dir)
                        for (root, dirs, files) in os.walk(goto):
                            for file in files:
                                if (file.lower().endswith('.py') | 
                                    file.lower().endswith('.pyc')) and 
                                    file != '__init__.py':
                                    print('file: ', file)
                                    # will change to os.remove once finsihed
    except:
        print('Unable to delete files')


if __name__ == "__main__":
    current = os.getcwd()
    delete_py(current, 'migrations')

-查询将在DECLARE @mockup TABLE(agent_name varchar(100),agent_department varchar(100)); 中读取您的SELECT

CTE

结果

WITH cte AS
(
    select [agent_name], [agent_department], count(*) as [row_count]
    from @mockup
    where [agent_name] IS NOT NULL
    group by [agent_name],[agent_department]
)
SELECT agent_name,agent_department,row_count FROM cte
UNION ALL SELECT NULL,NULL,0 WHERE (SELECT COUNT(*) FROM cte)=0;

您看到的是,结果集按原样称为 ,而有一个agent_name agent_department row_count NULL NULL 0 查询,该查询仅在cte没有行的情况下才提供。

现在我们将一些数据插入表中

UNION ALL SELECT

现在是新结果

INSERT INTO @mockup VALUES('blah','blub');
WITH cte AS
(
    select [agent_name], [agent_department], count(*) as [row_count]
    from @mockup
    where [agent_name] IS NOT NULL
    group by [agent_name],[agent_department]
)
SELECT agent_name,agent_department,row_count FROM cte
UNION ALL SELECT NULL,NULL,0 WHERE (SELECT COUNT(*) FROM cte)=0;