我有一个表STOCK_REGISTER,其中我有列Id,ItmId,Qty,CreatedDate。并且每日交易数据包括向内,向外和所有项目。
现在我正在制作一份月度报告,我想在整个月内显示项目数量的日明智总和。我写了以下查询来执行此操作。
SELECT CONVERT(Date,CreatedDate) AS CreatedDate,ItmId, SUM(Qty)
FROM STOCK_REGISTER
GROUP BY CONVERT(Date,CreatedDate),ItmId
此查询返回正确的数据,但如果我要求2017年4月的数据,并且STOCK_REGISTER在4月5日没有任何记录,那么4月5日我不需要显示4月5日我需要0个值的数据
你能帮助我获得这类数据吗?
编辑:
我创建了一个查询,它给出了任何特定月份的所有日期,并且已经使用STOCK_REGISTER应用了左连接,但仍未解决我的问题。
declare @month int, @year int
set @month = 4
set @year = 2017
SELECT CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + A.Number AS STKFG_CREATED_DATE,
B.STKFG_ITM_ID,
0 AS OPENING_STOCK,
SUM(STKFG_QTY)
FROM master..spt_values A
LEFT JOIN STOCK_REGISTER_FG B
ON CONVERT(DATE,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + A.Number) = CONVERT(DATE,B.STKFG_CREATED_DATE)
AND C.ITM_ID = B.STKFG_ITM_ID
WHERE type = 'P'
AND (CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + A.Number ) <
DATEADD(mm,1,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) )
AND STKFG_TRAT_ID = 6
GROUP BY A.Number, B.STKFG_ITM_ID
ORDER BY B.STKFG_ITM_ID,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + A.Number
答案 0 :(得分:1)
感谢您的评论。
我找到了一个适合我的解决方案。
此处#TEMP_TABLE包含所有日期。
SELECT A.CREATED_DATE,B.ITM_NAME,ISNULL(C.STKFG_QTY,0)
FROM #TEMP_TABLE A
CROSS APPLY ITEM_MASTER B
LEFT JOIN ( SELECT CONVERT(DATE,STKFG_CREATED_DATE) AS STKFG_CREATED_DATE, STKFG_ITM_ID, SUM(STKFG_QTY) AS STKFG_QTY
FROM STOCK_REGISTER_FG GROUP BY CONVERT(DATE,STKFG_CREATED_DATE),STKFG_ITM_ID) C
ON CONVERT(DATE,A.CREATED_DATE) = CONVERT(DATE,C.STKFG_CREATED_DATE)
AND B.ITM_ID = C.STKFG_ITM_ID
ORDER BY B.ITM_NAME,A.CREATED_DATE
答案 1 :(得分:0)
尝试以下脚本。这里@tblData是你的实际表名。
declare @tblData table
(id int,datecolumn date)
INSERT INTO @tblData
(id,datecolumn)
SELECT 1,'2010-01-01' UNION ALL
SELECT 3,'2010-01-01' UNION ALL
SELECT 1,'2010-01-03' UNION ALL
SELECT 2,'2010-01-04' UNION ALL
SELECT 1,'2010-01-05' UNION ALL
SELECT 3,'2010-01-06' UNION ALL
SELECT 1,'2010-01-10' UNION ALL
SELECT 1,'2010-01-10' UNION ALL
SELECT 2,'2010-01-11' UNION ALL
SELECT 1,'2010-01-11' UNION ALL
SELECT 2,'2010-01-11' UNION ALL
SELECT 1,'2010-01-12' UNION ALL
SELECT 3,'2010-01-13'
DECLARE @MaxDate DATE,
@MinDate DATE,
@iDate DATE
DECLARE @DateSequence TABLE(
DATE1 DATE
)
SELECT @MaxDate = Convert(DATE,Max(datecolumn)),
@MinDate = Convert(DATE,Min(datecolumn))
FROM @tblData -- Put your month condition
SET @iDate = @MinDate
WHILE (@iDate <= @MaxDate)
BEGIN
INSERT @DateSequence
SELECT @iDate
SET @iDate = Convert(DATE,Dateadd(DAY,1,@iDate))
END
SELECT a.DATE1 ,isnull(sum(b.id),0) as total
FROM @DateSequence a left join @tblData b on a.DATE1=b.datecolumn
group by a.DATE1
谢谢,