2017-09-25 64 views
0

我知道這個代碼是錯誤的輸入應該是這個樣子怎麼給3個日期獲取的數據在SQL Server 3個特定日期

select Factory,Sum(quantity) from table where date='23-09-2017' and date='24-09-2017' and date='25-09-2017 group by factory 
+3

用'或'替換'和'。或更詳細地解釋你想要做什麼 – HoneyBadger

+0

老兄我想要3個特定日期的工廠的數量總和 像1列將工廠名稱和其他3列將數量3給定的日期.. – Sasank

+1

所以你想要樞軸以及?請編輯您的問題以添加示例數據和預期輸出。 – HoneyBadger

回答

0

選廠,SUM(數量)from表where日期(」 23-09-2017','24-09-2017','25-09-2017')出廠組

+0

錯誤:將varchar數據類型轉換爲日期時間數據類型導致超出範圍值 – Sasank

0

這可以使用BETWEEN,ORIN完成。

查詢

Using BETWEEN

select Factory, 
Sum(quantity) 
from table 
where [date] between '23-09-2017' and date='25-09-2017' 
group by factory; 

可用於BETWEEN,因爲你的日期是連續三個日期。

Using OR

select Factory, 
Sum(quantity) 
from table 
where date='23-09-2017' or date='24-09-2017' or date='25-09-2017' 
group by factory; 

Using IN

select Factory, 
Sum(quantity) 
from table 
where date in ('23-09-2017','24-09-2017','25-09-2017') 
group by factory; 
+0

如何在該日期使用cast在 – Sasank

+0

中使用@Sasank:那麼,您是否將日期存儲爲'varchar'? – Wanderer

0

請嘗試 '在' 如果日期無法範圍不同,或者如果日期範圍之間使用。

select Factory, Sum(quantity) from table1 
WHERE Convert(Date, datefield) in '2017-09-23','2017-09-24','2017-09-25') 
group by Factory 

select Factory, Sum(quantity) from table1 
where Convert(Date, datefield)between '2017-09-23' and '2017-09-25' 
group by Factory 
+0

errro:從字符串轉換日期或時間時轉換失敗 – Sasank

0

您可以尋找這樣的:

select Factory, 
     SUM(CASE WHEN date='23-09-2017' THEN quantity END) '23-09-2017' 
     SUM(CASE WHEN date='24-09-2017' THEN quantity END) '24-09-2017' 
     SUM(CASE WHEN date='25-09-2017' THEN quantity END) '25-09-2017' 
from table 
group by factory 
0
declare @date1 datetime, 
@date2 datetime, 
@date3 datetime 

select @date1 = '2017-09-24',@date2 = '2017-09-30',@date3 = '2017-03-31' 

select Fac 'Particular', 
sum(case when cast(tran_date as date) = cast(@date1 as date) then Qty 
else 0 end) AS '@date1', 
sum(case when cast(tran_date as date) = cast(@date2 as date) then Qty 
else 0 end )AS '@date2', 
sum(case when cast(tran_date as date) = cast(@date3 as date) then Qty 
else 0 end )AS '@date3' 
from [table] where (cast(tran_date as date) = cast(@date1 as date) 
OR cast(tran_date as date) = cast(@date2 as date) 
OR cast(tran_date as date) = cast(@date3 as date)) 
group by fac 
0

你可以這樣來做:

SELECT Factory, 
     SUM(quantity) 
FROM Table 
WHERE YEAR(date) = 2017 
    AND MONTH(date) = 09 
    AND DAY(date) IN (23, 24, 25) 
GROUP BY Factory 

我希望我幫助。

0

當你在sql中調用像'20170922'這樣的特定日期時,它將搜索22 09 2017 00:00時間,所以你應該在查詢中使用BETWEEN。預期的查詢應該看起來像;

Select SUM(quantity),Datepart(day,Date),Factory 
FROM table 
Where (Date BETWEEN '2017-09-23' AND '2017-09-24') 
       OR (Date BETWEEN '2017-09-24' AND '2017-09-25') 
Group By Factory ,DATEPART(day,Date)