假设我有一个表(在 MySQL 中),例如:
CREATE TEMPORARY table IF NOT EXISTS tbl
(
REF_REQ_ID int AUTO_INCREMENT PRIMARY KEY,
FunctionalArea varchar(200),
Industry varchar(200)
);
INSERT INTO tbl
SELECT 1, 'IT Jobs', 'IT related Jobs' UNION ALL
SELECT 2, 'HR Jobs', NULL UNION ALL
SELECT 3, NULL, 'HR related Jobs' UNION ALL
SELECT 4, NULL, 'IT related Jobs' UNION ALL
SELECT 5, NULL, NULL UNION ALL
SELECT 6, 'IT Jobs', 'IT related Jobs' UNION ALL
SELECT 7, 'HR Jobs', NULL UNION ALL
SELECT 8, NULL, 'HR related Jobs' UNION ALL
SELECT 9, 'HR Jobs', NULL;
我想在单列(distinct
值)中加入和组合两列并排序NoOfJobs
,我该如何实现?
预期结果
JobTitle NoOfJobs
HR Jobs 3
IT related Jobs 3
HR related Jobs 2
IT Jobs 2
如果您有任何疑问或问题内容不合适,请发表评论。
数据库是 MySQL,我知道如何在 SQL Server 中实现这一点。
只需运行此查询(对于 MS SQL Server):
DECLARE @tbl table
(
REF_REQ_ID int IDENTITY(1,1),
FunctionalArea varchar(200),
Industry varchar(200)
)
INSERT INTO @tbl
SELECT 'IT Jobs', 'IT related Jobs' UNION ALL
SELECT 'HR Jobs', NULL UNION ALL
SELECT NULL, 'HR related Jobs' UNION ALL
SELECT NULL, 'IT related Jobs' UNION ALL
SELECT NULL, NULL UNION ALL
SELECT 'IT Jobs', 'IT related Jobs' UNION ALL
SELECT 'HR Jobs', NULL UNION ALL
SELECT NULL, 'HR related Jobs' UNION ALL
SELECT 'HR Jobs', NULL
SELECT
JobTitle As JobTitle,
COUNT(REF_REQ_ID) As NoOfJobs
FROM
(SELECT
FunctionalArea As JobTitle,
REF_REQ_ID
FROM @tbl
UNION
SELECT
Industry As JobTitle,
REF_REQ_ID
FROM @tbl)t
WHERE JobTitle IS NOT NULL
GROUP BY JobTitle
ORDER BY NoOfJobs desc
它会给我预期的结果,但不幸的是 MySQL 不支持UNION
同一张表(临时)。
MySQL 读者:我怎样才能达到预期的效果?
SQL Server 读者:做同样的替代方法?