基本上我想得到两个计数。第一个计数是记录数。第二个计数是带有数据的记录数。这两个计数来自名为调查的表,该表并不具有所有的州名称。因此,我将其与另一个表UsState结合在一起以获取所有状态名称。我整理了语法,但出现错误。
SELECT
Name as State,
count (*)from NamrsFrozen2017.Investigation2017 where FiscalYear = 2017 AND StateName in (SELECT distinct StateName FROM [NamrsFrozen2017].[Investigation2017] WHERE (not ReportDate = '' ))[Report Date Records],
count (*) from NamrsFrozen2017.Investigation2017 WHERE FiscalYear = 2017 AND ReportDate != '' AND StateName in (SELECT distinct StateName FROM [NamrsFrozen2017].[Investigation2017] WHERE (not ReportDate = '' ))[Report Date Records with Data]
From
(SELECT DISTINCT Name FROM NamrsFullDw.UsState) s
LEFT JOIN NamrsFrozen2017.Investigation2017 c ON s.Name = c.StateName AND c.FiscalYear = 2017
GROUP BY Name
Order by Name
答案 0 :(得分:0)
一些相关的子查询将为您提供帮助。它们看起来像内联选择,但使用对内联查询之外的表的引用。像这样:
SELECT
Name as State,
(SELECT COUNT(*)
FROM NamrsFrozen2017.Investigation2017
--I would think you want to view count of records for the current state, and not ALL states
-- and not ALL states. So filter like this:
WHERE FiscalYear = 2017 AND StateName = s.Name -- <-Correlated
--Don't need a full list, like you had before
-- (SELECT distinct StateName FROM [NamrsFrozen2017].[Investigation2017] WHERE (not ReportDate = '' ))
) AS [Report Date Records],
(SELECT COUNT(*)
FROM NamrsFrozen2017.Investigation2017
WHERE FiscalYear = 2017 AND StateName = s.Name -- <- correlated
AND ReportDate != '' --or maybe ReportDate IS NOT NULL
--Don't need to query the full table after correlating this to your FROM clause
-- in (SELECT distinct StateName FROM [NamrsFrozen2017].[Investigation2017] WHERE (not ReportDate = '' ))
) AS [Report Date Records with Data]
FROM
(SELECT DISTINCT Name FROM NamrsFullDw.UsState) s
LEFT JOIN NamrsFrozen2017.Investigation2017 c
ON s.Name = c.StateName AND c.FiscalYear = 2017
GROUP BY s.Name
ORDER BY s.Name
这可能会进行更多优化,但是我对您的数据不熟悉,或者不清楚您到底要用原始查询来完成什么。
答案 1 :(得分:0)
评论太久了。
您收到的语法错误是因为内联子查询的格式不正确。您不能以COUNT(*)
函数开头;它们每个都需要完整的SELECT
语句。然后,需要将每一个都用括号括起来。
这就是您的查询的样子。
SELECT
Name AS State
,(
SELECT
COUNT(*)
FROM
NamrsFrozen2017.Investigation2017
WHERE
FiscalYear = 2017
AND StateName IN
(
SELECT DISTINCT StateName
FROM NamrsFrozen2017.Investigation2017
WHERE ReportDate <> ''
)
) AS [Report Date Records]
,(
SELECT
COUNT(*)
FROM
NamrsFrozen2017.Investigation2017
WHERE
FiscalYear = 2017
AND ReportDate != ''
AND StateName IN
(
SELECT DISTINCT StateName
FROM NamrsFrozen2017.Investigation2017
WHERE (NOT ReportDate = '')
)
) AS [Report Date Records with Data]
FROM
(SELECT DISTINCT Name FROM NamrsFullDw.UsState) AS s
LEFT JOIN
NamrsFrozen2017.Investigation2017 AS c
ON
s.Name = c.StateName
AND c.FiscalYear = 2017
GROUP BY
Name
ORDER BY
Name;
这里还有一个第二个问题,那就是该查询是否会执行您期望的操作。就Larnu的评论而言,聚合函数在不同情况下对NULL
的处理方式不同。但是,如果没有可供测试的样本数据,我无法确定此功能版本的查询是否会返回您想要的结果。