Sql Query结果格式化

时间:2017-04-18 13:33:32

标签: sql-server

我正在执行查询,我希望输出为

CompanyType SFCount SNCount
Customer     47       3
Vendor       8        3
Internal     11       1

但输出结果如下:

enter image description here

2 个答案:

答案 0 :(得分:1)

将查询包含在子查询中并sum()结果:

 SELECT sub.CompanyType, sum(sub.sfcount) as sfcount, sum(sub.sncount) as sncount
 FROM ( 
        SELECT businesstype AS [CompanyType],
            count(*) AS [SFCount],
            '' AS [SNCount]
        FROM account
        WHERE businesstype IN ( 'Customer', 'Vendor', 'Internal')       )
        GROUP BY businesstype

        UNION

        SELECT 'Customer' AS [CompanyType],
            '' AS [SFCount],
            count(*) AS [SNCount]
        FROM sn_core_company
        WHERE customer = 1

        UNION

        SELECT 'Vendor' AS [CompanyType],
            '' AS [SFCount],
            count(*) AS [SNCount]
        FROM sn_core_company
        WHERE vendor = 1

        UNION

        SELECT 'Internal' AS [CompanyType],
            '' AS [SFCount],
            count(*) AS [SNCount]
        FROM sn_core_company
        WHERE u_internal = 1

 ) sub
 GROUP BY businesstype;

答案 1 :(得分:-3)

只需在所有选择语句中添加where条件

其中SFCount>根据您的要求,0和SNCount> 0