如何在sql server中获取最近3个月的名称

时间:2015-11-25 06:49:27

标签: sql sql-server

我的查询

SELECT CONVERT(CHAR, DATENAME(MONTH, IssueDate)) AS MonthName,
       ItemId,
       COUNT(CONVERT(VARCHAR, IssueDate, 6)) AS WorkingDays
FROM   dbo.Issue AS Issue
GROUP BY
       CONVERT(CHAR, DATENAME(MONTH, IssueDate)),
       ItemId
HAVING (ItemId = 427)

查询明智显示 enter image description here

但我需要

but my need

PLZ尽快解决了这个问题。

5 个答案:

答案 0 :(得分:0)

尝试以下查询

$http.get(baseUrl, {
    headers: someHeader, //header for authentication
    params: {
       id: id
    },
    responseType: 'arraybuffer'
})

答案 1 :(得分:0)

我不确定这是否适合您。我只是简单地创建一个类似于你的情况的表,并在我身边进行测试。 请试试。

WITH Last3Month AS
(
    SELECT DISTINCT TOP 3 MONTH(IssueDate) AS Mth
    FROM Issue
    ORDER BY Mth DESC
)
SELECT CONVERT(CHAR, DATENAME(MONTH, IssueDate)) AS MonthName,
        ItemId,
        COUNT(CONVERT(varchar, IssueDate, 6)) AS WorkingDays
FROM dbo.Issue AS Issue
INNER JOIN Last3Month ON MONTH(Issue.IssueDate) = Last3Month.Mth
GROUP BY CONVERT(CHAR, DATENAME(MONTH, IssueDate)), ItemId, Last3Month.Mth
HAVING (ItemId = 427)
ORDER BY Last3Month.Mth

答案 2 :(得分:0)

好的@Imrul Kaesh你现在的问题是什么?

根据您提供的数据集,我使用查询选择ItemId = 427和ItemId = 430的最近3个月记录。结果如下所示:

enter image description here

请记住,您只能使用INNER JOIN而不能使用LEFT OUTER JOIN。谢谢。

答案 3 :(得分:0)

我在查询 -

下方正确获得仅月份名称

SELECT DATENAME(MONTH, dt) AS Monthnames, ItemId FROM (SELECT DISTINCT TOP (3) DATEADD(MONTH, DATEDIFF(MONTH, 0, IssueDate), 0) AS dt, ItemId FROM dbo.Issue WHERE (ItemId = 452) ORDER BY dt DESC) AS t Now show this

但我需要ItemID,ItemName,WorkingDays,IssueQty和MonthNames my need this format

答案 4 :(得分:0)

对不起@Imrul Kaesh,查询上有一些错误。我没有用ItemId过滤最后3个月。

我已经更新了我的查询,请试试:

WITH Last3Month AS
(
    SELECT DISTINCT TOP 3 MONTH(IssueDate) AS Mth
    FROM Issue
    WHERE ItemId = 452      --Please add this WHERE Clause
    ORDER BY Mth DESC
)
SELECT CONVERT(CHAR, DATENAME(MONTH, IssueDate)) AS MonthName,
        ItemId,
        COUNT(CONVERT(varchar, IssueDate, 6)) AS WorkingDays
FROM dbo.Issue AS Issue
INNER JOIN Last3Month ON MONTH(Issue.IssueDate) = Last3Month.Mth
GROUP BY CONVERT(CHAR, DATENAME(MONTH, IssueDate)), ItemId, Last3Month.Mth
HAVING (ItemId = 452)
ORDER BY Last3Month.Mth