我有一个运行良好的MS Access查询,但是我不知道如何在SQL Server中编写此查询。
MS Access查询:-
SELECT lp.PortfolioID,
Count(IIf(lp.Data_Status = 'Prelim Collection', 1, Null)) AS Prelim_Collection_Cnt,
Count(IIf(lp.Data_Status = 'Final Collection', 1, Null)) AS Final_Collection_Cnt,
Count(IIf(lp.Data_Status = 'Prelim Entry', 1, Null)) AS Prelim_Entry_Cnt,
Count(IIf(lp.Data_Status = 'Final Entry', 1, Null)) AS Final_Entry_Cnt,
Count(IIf(lp.Data_Status = 'Prelim QC', 1, Null)) AS Prelim_QC_Cnt,
Count(IIf(lp.Data_Status = 'Final QC', 1, Null)) AS Final_QC_Cnt
FROM (
SELECT DISTINCT p.PortfolioID, p.Data_Status
FROM Late_Portfolios AS p
WHERE p.TimeStamp BETWEEN #10/01/2018# AND #10/31/2018#) AS lp
GROUP BY lp.PortfolioID;
答案 0 :(得分:1)
您最好的选择是切换到CASE语句,因为这些语句几乎可以在阳光下的每个RDBMS中使用(Access除外...我无法想象为什么它仍然不支持此功能,但这就是您的MS)。除此之外,您还想将日期文字转换为ISO8601格式YYYY-MM-DD
并将其封装在单引号而不是哈希中。
SELECT lp.PortfolioID,
COUNT(CASE WHEN lp.Data_Status = 'Prelim Collection' THEN 1 END) AS Prelim_Collection_Cnt,
COUNT(CASE WHEN lp.Data_Status = 'Final Collection' THEN 1 END) AS Final_Collection_Cnt,
COUNT(CASE WHEN lp.Data_Status = 'Prelim Entry' THEN 1 END) AS Prelim_Entry_Cnt,
COUNT(CASE WHEN lp.Data_Status = 'Final Entry' THEN 1 END) AS Final_Entry_Cnt,
COUNT(CASE WHEN lp.Data_Status = 'Prelim QC' THEN 1 END) AS Prelim_QC_Cnt,
COUNT(CASE WHEN lp.Data_Status = 'Final QC' THEN 1 END) AS Final_QC_Cnt
FROM
(
SELECT DISTINCT
p.PortfolioID,
p.Data_Status
FROM Late_Portfolios AS p
WHERE p.TimeStamp BETWEEN '2018-10-01' AND '2018-10-31'
) AS lp
GROUP BY lp.PortfolioID;
答案 1 :(得分:0)
我的解析器仅抱怨您的日期,可以使用“ yyyymmdd”
'SELECT ... WHERE discovery_time > 1800'
答案 2 :(得分:0)
该逻辑也应在SQL Server
中起作用,如果您的版本较低,则可以进行条件聚合:
select lp.PortfolioID,
sum(case when lp.Data_Status = 'Prelim Collection' then 1 else 0 end),
from ( <query> ) AS lp
group by lp.PortfolioID;
只需以20180110
格式ANSI SQL
传递您的日期:
where p.TimeStamp >= '20180110' AND p.TimeStamp >= '20181031'