SQL Server查询运行 - 但不返回任何数据

时间:2018-06-11 15:47:56

标签: sql-server database mssql-jdbc

尽管运行了以下查询,但未返回任何数据。该查询将列拆分为JudgmentMonthConsumerCommercial。我对SQL Server的了解不是很好,但我猜测没有给出日期参数,因此没有返回数据。我不确定在> =和< =

之后手动输入日期
WITH dset AS
(
    SELECT 
        COUNT(category) AS Volumes, 
        MONTH(creation_date) AS JudgmentMonth, 
        transaction_type, 
        REPLACE(record_type, 3, 2) AS RecordType
    FROM 
        table 
    WHERE 
        transaction_type = 'jg' 
        AND category = 'CCJ' 
        AND CAST(creation_date AS DATE) >=  CONVERT(VARCHAR(12), GETDATE(), 101) 
        AND CAST(creation_date AS DATE) <=  CONVERT(VARCHAR(12), GETDATE(), 101)
    GROUP BY 
        MONTH(creation_date), transaction_type, REPLACE(record_type, 3, 2)
)
SELECT    
    x.JudgmentMonth,
    MAX(CASE x.RecordType WHEN '1' THEN x.Volumes END) CONSUMER,
    MAX(CASE x.RecordType WHEN '2' THEN x.Volumes END) COMMERCIAL
FROM    
    (SELECT    
         r.JudgmentMonth, r.RecordType, r.Volumes
     FROM    
         dset r) x
GROUP BY 
    x.JudgmentMonth

2 个答案:

答案 0 :(得分:1)

你给它的日期:你给它getdate()两次!

creation_date >= getdate and creation_date <= getdate

相同
creation_date = getdate()

因此,除非您的creation_date与当前日期/时间完全匹配,否则您将无法获得更多。

答案 1 :(得分:1)

将您的专栏creation_date转换为date会使您的查询无法进行SARG。 假设您想要的是当前日期的数据,我建议:

...
WHERE ...
  AND creation_date >= CONVERT(date, GETDATE())
  AND creation_date < CONVERT(date, DATEADD(DAY, 1, GETDATE()))
GROUP BY...

这将创建一个SARGable查询,因​​此执行速度远远快于转换表达式的两面。