(右(将varchar 103转换为120 DATETIME以将结果显示为120)

时间:2016-05-25 12:22:51

标签: sql vba sql-server-2008 sql-server-2008-r2 access-vba

我有以下查询显示我需要的任何特定日期的所有正确结果。但是,我的客户希望能够一次搜索任何一个月,避免单独选择每月的每一天。我假设我能够转换日期的一部分(月+年),将其转换为另一种格式,然后使用它。目前显示为05/2016(103),但我需要能够搜索2016-05%(120)才能显示结果。 代码将放在Access VBA表单中。

SELECT 
    os.shop, os.prefix, 
    Rep_date AS FDate, 
    SUM(RC) AS Fulfilled, 
    SUM(RF) AS Refunded, 
    SUM(OS) AS TotalOS, 
    SUM(CA) AS TotalCA, 
    SUM(RET) AS TotalRET, 
    SUM(LOST) AS TotalLOST, 
    SUM(SHOR) AS TotalSHOR, 
    SUM(Total) AS Total, 
    CAST((CAST(SUM(RC) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS RCPC, 
    CAST((CAST(SUM(RF) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS RFPC, 
    CAST((CAST(SUM(OS) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS OSPC, 
    CAST((CAST(SUM(CA) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS CAPC, 
    CAST((CAST(SUM(RET) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS RETPC, 
    CAST((CAST(SUM(LOST) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS LOSTPC, 
    CAST((CAST(SUM(SHOR) AS DECIMAL(9, 4)) / CAST(SUM(Total) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS SHORPC, 
    SUM(Orders) AS TotalOrders, 
    SUM(AmazonShipped) AS AmazonShipped, 
    SUM(AmazonCancelled) AS AmazonCancelled, 
    SUM(AmazonUnshipped) AS AmazonUnshipped, 
    CAST((CAST(SUM(AmazonShipped) AS DECIMAL(9, 4)) / CAST(SUM(Orders) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS AmazonShippedPC, 
    CAST((CAST(SUM(AmazonCancelled) AS DECIMAL(9, 4)) / CAST(SUM(Orders) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS AmazonCancelledPC, 
    CAST((CAST(SUM(AmazonUnshipped) AS DECIMAL(9, 4)) / CAST(SUM(Orders) AS DECIMAL(9, 4))) AS DECIMAL(9, 4)) AS AmazonUnshippedPC, 
    p.Description 
FROM 
    OrderStatusSummary os 
LEFT JOIN 
    Prefix p ON os.prefix = p.prefix 
GROUP BY 
    Rep_date, os.shop, os.prefix, p.Description 
HAVING 
   (CAST(CONVERT(nvarchar(10), Rep_date, 120) AS DATETIME) = CONVERT(DATETIME, '25/05/2016', 103)) 
ORDER BY 
    CAST(CONVERT(nvarchar(10), Rep_date, 120) AS DATETIME) DESC

以上是以完整日期搜索的方式,以下是我试图按月/年搜索的内容,以向您展示我正在努力实现的目标。但它不起作用。

HAVING (RIGHT(CONVERT(nvarchar(10), Rep_date, 103),7) = '05/2016') 

我改变的代码的唯一部分是与顶部块相比的HAVING。

2 个答案:

答案 0 :(得分:1)

步骤1 - 使用您的vba代码创建名为startDate和endDate的2个变量。将startDate作为有问题的年份的第一天,并在下个月的第一天结束。

步骤2 - 使用这些变量作为具有此逻辑的sql的查询参数:

where rep_date >= startDate
and rep_date < endDate

答案 1 :(得分:0)

几天之后回到原点后,我已经回答了我自己的问题。...

由于Rep_date是文本字段而不是日期字段,因此我不需要对其进行任何日期转换。

HAVING LEFT(Rep_date, 7) = '2016-05' 

工作得很好。