1

我想获取特定日期输入的所有记录,例如今天:

我的桌子

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

它返回三个记录: 结果

一个问题是第二列没有名称。为什么?另外,我只想返回一条包含三行的记录,而不是包含 2 个字段的 3 条单独记录。

4

3 回答 3

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
于 2012-09-21T15:20:58.240 回答
1

您需要将您的 varchar 转换为日期时间。我想你想给CountsCount(*) 分配别名

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
于 2012-09-21T15:31:23.880 回答
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
于 2012-09-21T16:25:26.627 回答