我想获取在特定日期输入的所有记录,例如今天:
ALTER PROCEDURE [dbo].[SP_GET_QUEUESINFO_BY_DATE]
@date nvarchar = '2012-09-21'
AS
BEGIN
declare @dateStart nvarchar(50) = @date + ' 00:00:00.0'
declare @dateEnd nvarchar(50) = @date + ' 23:59:59.437';
declare @returnData table (allQueue int,inQueue int,outQueue int)
SELECT 'table1' as table_name, COUNT(*)
FROM Queue as Counts
UNION ALL
SELECT 'table2' as table_name,COUNT(*) FROM Queue as Counts
WHERE QueueDate BETWEEN @dateStart AND @dateEnd
AND QueueNumIn != 0
END
已编辑: 我现在编辑了我的代码:
ALTER PROCEDURE [dbo].[SP_GET_QUEUESINFO_BY_DATE]
AS
BEGIN
declare @date2 datetime
set @date2= '2012-09-21'
SELECT 'AllQueue' as table_name, COUNT(*)
FROM Queue as sdfds
UNION ALL
SELECT 'InQueue' as table_name,COUNT(*)
FROM Queue as sdfds
WHERE QueueDate >=@date2
AND QueueNumIn != 0
UNION ALL
SELECT 'OutQueue' as table_name, COUNT(*) FROM Queue as sdfds
WHERE QueueDate >=@date2
AND QueueNumOut != 0
END
它返回三条记录:
一个问题是第二列没有名称。为什么?另外,我想只返回一个有三行的记录,而不是三个有两个字段的单独记录。
答案 0 :(得分:1)
如果你只想要那些在特殊日期的人,那就不知道为什么要全部归还。
另外,最好不要在日期之间使用
ALTER PROCEDURE [dbo].[SP_GET_QUEUESINFO_BY_DATE]
@date datetime = '2012-09-21'
AS
BEGIN
select count(*) as 'AllQueue' ,
sum(case when QueueDate >=@date and QueueNumIn != 0 THEN 1 else 0 end) as 'InQueue',
sum(case when QueueDate >=@date and QueueNumOut != 0 THEN 1 else 0 end) as 'OutQueue'
from Queue
END
这应该有效。
这会给你类似的东西
Allqueue inqueue, outqueue
----------------------------------------------------
11 | 8 | 10
答案 1 :(得分:1)
您需要将varchar转换为datetime。我想你想把Counts
别名分配给Count(*)
ALTER PROCEDURE [dbo].[SP_GET_QUEUESINFO_BY_DATE]
@date nvarchar = '2012-09-21'
AS
BEGIN
declare @dateStart DATETIME = CAST(@date AS DATETIME)
declare @dateEnd DATETIME = DATEADD(hh,24,CAST(@date AS DATETIME))
declare @returnData table (allQueue int,inQueue int,outQueue int)
select 'table1' as table_name,COUNT(*) as Counts from QUEUE AS tb1
union all
select 'table2' as table_name,COUNT(*) as Counts from QUEUE AS tb2 where QueueDate >= @dateStart and QueueDate < @dateEnd and QueueNumIn !=0
END
答案 2 :(得分:0)
此代码已经过工作,并且是ElVieejo编辑的代码
ALTER PROCEDURE [dbo].[SP_GET_QUEUESINFO_BY_DATE]
AS
BEGIN
declare @date2 datetime
set @date2= '2012-09-21'
select COUNT(QueueID) ,
sum(case when QueueNumIn != 0 THEN 1 else 0 end) as 'InQueue',
sum(case when QueueNumOut != 0 THEN 1 else 0 end) as 'OutQueue'
from Queue where QueueDate >= @date2
END