MS SQL - 按日期和计数分组

时间:2018-03-09 01:39:43

标签: sql-server

希望你能指导我这个。

以下是我的情景:

我为商人提供了一张桌子。

因此,商家需要每周提交库存和交货数量。只要他们提交一周的库存或交货计数,他们就可以每天发送。

现在,我的要求是创建活动报告。

Activity Report

正如您在屏幕截图中看到的那样,如果有商家,例如今天, 并且他今天发送交货和库存盘点,活动报告应该计算并显示它。

这是我的问题:



select	a.TimeInDtRcvd,
        b.deliveryCount,
        c.inventoryCount
from    BigEMerchandiser.dbo.tbl_Attendance as a

       left join (select count(CreatedBy) as deliveryCount, CreatedBy, DtRcv
                  from BigEMerchandiser.dbo.tbl_Delivery_H
                  group by CreatedBy, DtRcv) as b on a.CellNum = b.CreatedBy

     left join (select count(CreatedBy) as inventoryCount, CreatedBy, DtRcv
                from BigEMerchandiser.dbo.tbl_Inventory_H
                group by CreatedBy, DtRcv) as c on a.CellNum = c.CreatedBy

and 	convert(date, a.TimeInDtRcvd) >= convert(date, '01/01/2018') and convert(date, a.TimeInDtRcvd) <= convert(date, '03/30/2018')
and 	a.TimeIn is not null
and 	a.TimeOut is not null

group by a.TimeInDtRcvd, b.deliveryCount, c.inventoryCount
&#13;
&#13;
&#13;

希望我能清楚地解释自己。如果有详细信息我可以提供,请立即提供。我正在使用MS SQL SERVER 2014.谢谢。

修改 我已经解决了它做了一些试验和错误以及搜索。 这是我的新查询:

&#13;
&#13;
SELECT	a.CellNum,
		e.LName + ' ' + e.FName as diser,
		cast(a.TimeInDtRcvd as date) as date,
		a.TimeIn as timeIn,
		a.TimeOut as timeOut,
		COUNT(DISTINCT b.TransCtr) AS deliveryCount,
		COUNT(DISTINCT c.TransCtr) AS inventoryCount,
		COUNT(DISTINCT d.TransCtr) AS abisCount,
		overall_count = count(*) over()
from	BigEMerchandiser.dbo.tbl_Attendance as a

		left outer join BigEMerchandiser.dbo.tbl_Delivery_H as b 
		ON b.CreatedBy = a.CellNum
		and cast(a.TimeInDtRcvd as date) = cast(b.DtRcv as date)


		left outer join BigEMerchandiser.dbo.tbl_Inventory_H as c 
		ON c.CreatedBy = a.CellNum

		and cast(a.TimeInDtRcvd as date) = cast(c.DtRcv as date)


		left outer join BigEMerchandiser.dbo.tbl_Abis_H as d 
		ON d.CreatedBy = a.CellNum
		and cast(a.TimeInDtRcvd as date) = cast(d.DtRcv as date)
    
    
   GROUP BY a.CellNum, 
        e.LName, 
        e.FName,
        a.TimeInDtRcvd,
        a.TimeIn,
        a.TimeOut
   ORDER BY diser asc, a.TimeInDtRcvd desc
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

Messed up

You are doing a count(CreatedBy) and that is a group by
Surprise you get 1