SQL Count of columns导致表中的所有现有日期

时间:2013-05-08 13:59:45

标签: sql

我有一个表DTTransaction和DTHotelTransaction,其中TransactionID是以后的前键和外键中的主键。

Columns in DTTransaction  :machinename(varchar),BookedOn(datetime),TransactionID(int) 
Columns in DTHotelTransaction :HCOMCID(int) ,TransactionID 

要求:

对于DTTransaction中的每个BookedOn值,我想要这些(415428,415429,415430,415431,415432)HCOMCID的机器名称和机器名数。

我正在尝试:

select DTTransaction.machinename,count(DTTransaction.machinename) from DTTransaction   
join DTHotelReservation on DTTransaction.TransactionID =      
DTHotelReservation.TransactionID
and DTHotelReservation.HCOMCID in (
415428,
415429,
415430,
415431,
415432)
where convert(varchar(10),BookedOn,101)='04/10/2013'
group by DTTransaction.machinename

但它只会给出特定日期。我想得到所有现有BookedOn值的计数。

提前致谢。

1 个答案:

答案 0 :(得分:1)

如果您想要所有日期的总和,只需删除where子句:

select DTTransaction.machinename, count(DTTransaction.machinename)
from DTTransaction join
     DTHotelReservation
     on DTTransaction.TransactionID = DTHotelReservation.TransactionID and
        DTHotelReservation.HCOMCID in (415428, 415429, 415430, 415431, 415432)
group by DTTransaction.machinename

如果您希望按日期显示结果,请将其包含在group by中。例如,

select DTTransaction.machinename, convert(varchar(10),BookedOn,101), count(DTTransaction.machinename)
from DTTransaction join
     DTHotelReservation
     on DTTransaction.TransactionID = DTHotelReservation.TransactionID and
        DTHotelReservation.HCOMCID in (415428, 415429, 415430, 415431, 415432)
group by DTTransaction.machinename, convert(varchar(10),BookedOn,101)
order by 1, MAX(BookedOn)

我添加了order by子句,因此每个计算机名称中的结果将按日期排序。