想要计数,但每次记录都会重复1次

时间:2015-02-10 07:11:41

标签: sql sql-server subquery correlated-subquery inner-query

我想要一个计数,但每次记录都会重复1次。你能建议做什么吗?

SELECT Count(*),
       innerTable.*
FROM   (SELECT (SELECT NAME
                FROM   tours
                WHERE  tours.id = tourbooking.tourid)         AS NAME,
               (SELECT url
                FROM   tours
                WHERE  tours.id = tourbooking.tourid)         AS Url,
               (SELECT TOP 1 NAME
                FROM   tourimages
                WHERE  tourimages.tourid = tourbooking.tourid
                ORDER  BY id ASC)                             AS ImageName,
               (SELECT duration + ' ' + CASE WHEN durationtype = 'd' THEN
                       'Day(s)' WHEN
                       durationtype =
                       'h' THEN 'Hour(s)' END
                FROM   tours
                WHERE  tours.id = tourbooking.tourid)         AS Duration,
               (SELECT Replace(Replace('<a> Adult(s) - <c> Children', '<a>', Sum
                               (CASE
                                       WHEN [type] = 1 THEN 1
                                       ELSE 0
                                END)),
                       '<c>',
                       Sum(CASE
                       WHEN [type] = 2 THEN 1
                       ELSE 0
                       END))
                FROM   tourperson
                WHERE  tourperson.bookingid = tourbooking.id) AS TotalPassengers
               ,
               startdate,
               createddate                                    AS BookingDate,
               id                                             AS BookingID,
               [status],
               serviceprice
        FROM   tourbooking
        WHERE  memberid = 6)AS innerTable
GROUP  BY innerTable.NAME,
          innerTable.bookingdate,
          innerTable.bookingid,
          innerTable.duration,
          innerTable.imagename,
          innerTable.serviceprice,
          innerTable.startdate,
          innerTable.status,
          innerTable.totalpassengers,
          innerTable.url 

1 个答案:

答案 0 :(得分:0)

您从tourbooking选择记录。您选择的其中一列是id。这可能是表的主键,因此是唯一的。 (如果没有,你应该快点改名。)

您将此ID称为BookingID,它是您分组的列之一。因此,您在tourbooking中为每条记录获得一条结果记录。这样一个&#34;组内的记录数量&#34;当然是1;它是您选择并显示的一条记录。

如果您构建真实的组,每个天说出一个结果记录,那么您将获得真正的计数,例如:每天预订的数量。