通过SQL构建Matrix

时间:2017-09-27 07:21:37

标签: sql sql-server pivot

我正在使用来自计算公司的模式的两个查询,但我正在努力如何将它们组合在一起,将列作为国家和行业作为行,并相应地给公司计数。

select g.simpleindustrydescription,  count(c.companyid) as companycount from ciqcompany c
join ciqsimpleindustry g on g.simpleIndustryid = c.simpleIndustryid
join ciqbusinessdescription b on b.companyid = c.companyid
group by g.simpleindustrydescription

select g.country,  count(c.companyid) as companycount from ciqcompany c
join ciqcountrygeo g on g.countryid = c.countryid
join ciqbusinessdescription b on b.companyid = c.companyid     
group by g.country 

预期输出:

             Country A   Country B   Country C
Industry A       5         5           6
Industry B       3         3           4
Industry C       4         8           6

1 个答案:

答案 0 :(得分:0)

由于缺少真实的示例数据,这里有一个基于一些虚拟记录的简单数据透视示例:

gradle bootRun

无论如何,如果您正在处理未知数量的国家/地区,您可能需要稍微扩展此示例并使用动态SQL来构建pivot语句。在某个地方有一个例子,但必须搜索它......

我的例子的结果:

CREATE TABLE #tCountry
(
   ID INT
  ,Name NVARCHAR(100)
);

INSERT INTO #tCountry VALUES (1, 'Country A'), (2, 'Country B'), (3, 'Country C');

CREATE TABLE #tIndustry
(
   ID INT
  ,Name NVARCHAR(100)
);

INSERT INTO #tIndustry VALUES (1, 'Industry A'), (2, 'Industry B'), (3, 'Industry C');


CREATE TABLE #tMapping
(
   ID INT
  ,CountryID INT
  ,IndustryID INT
  ,Name NVARCHAR(100)
);

INSERT INTO #tMapping VALUES (1, 1, 1, 'Country A Industry A - 1'), (2, 1, 1, 'Country A Industry A - 2');
INSERT INTO #tMapping VALUES (3, 1, 2, 'Country A Industry B - 1'), (4, 1, 2, 'Country A Industry b - 2'), (5, 1, 2, 'Country A Industry b - 3');
INSERT INTO #tMapping VALUES (6, 2, 1, 'Country B Industry A - 1');

DECLARE @lCountries NVARCHAR(max) = N'';
DECLARE @stmt NVARCHAR(MAX) = N'';

SELECT @lCountries += N', ' + QUOTENAME(CountryName)
FROM(
SELECT DISTINCT tc.Name CountryName
  FROM #tCountry tc
  JOIN #tMapping tm ON tm.CountryID = tc.ID
) x;

SELECT @lCountries = STUFF(@lCountries, 1, 2, '');

SELECT @stmt = 'SELECT *
                  FROM
                  (
                  SELECT ti.Name IndustryName, tc.Name CountryName, COUNT(*) MappingCounter
                    FROM #tMapping tm
                    JOIN #tCountry tc ON tm.CountryID = tc.ID
                    JOIN #tIndustry ti ON tm.IndustryID = ti.ID
                    GROUP BY ti.Name, tc.Name
                  ) t
                  PIVOT (MAX(t.MappingCounter) FOR CountryName in (' + @lCountries + ')) AS x';

EXEC sp_executesql @stmt