sql join,从一个表中获取所有信息并从另一个表中计数

时间:2015-11-29 19:51:24

标签: sql-server

我有3个表,需要计算一个类型在预订表中出现的次数,并且如果它们没有出现,还会将其他类型显示为零。 我的sql看起来像这样,但它只给了我在预订表中的类型。

 SELECT        Types.Type, COUNT(Types.Type) AS Total
FROM            Booking INNER JOIN
                     Pitch ON Booking.Location_id = Pitch.Location_Id INNER JOIN
                     Types ON Pitch.Type_ID = Types.Type_ID
 WHERE        (MONTH(Booking.EndDate) = MONTH(GETDATE()) ) OR
                     (MONTH(Booking.StartDate) = MONTH(GETDATE()))
  GROUP BY Types.Type

这三个表是Booking,Pitch,Type 预订有Location_id,pitch有Location_id,Type_ID,Type有Type_ID

任何想法

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT 
Types.Type,
(SELECT  COUNT(*) FROM Pitch
            LEFT JOIN booking ON Pitch.Location_Id = booking.Location_Id
    WHERE Pitch.Type_ID = Types.Type_ID
            AND ( MONTH(Booking.EndDate) = month(GETDATE()) OR MONTH(Booking.StartDate) = month(GETDATE()) )
    ) AS total
From Types

答案 1 :(得分:0)

select types.type, COUNT(Booking.Location_id) AS "Total"
FROM   Pitch LEFT JOIN
         Booking
 ON Pitch.Location_Id = Booking.Location_id
 LEFT JOIN Types ON Pitch.Type_ID=Types.Type_ID
GROUP BY types.type

这为我提供了所有预订表所需的信息,然后我想过滤它以仅显示本月的预订。 香港专业教育学院试过这个

 select types.type, COUNT(Booking.Location_id) AS "Total"
 FROM   Pitch LEFT JOIN
         Booking
 ON Pitch.Location_Id = Booking.Location_id
 LEFT JOIN Types ON Pitch.Type_ID=Types.Type_ID
 where
 month(Booking.EndDate) = month(GETDATE())

 or month(Booking.StartDate) = month(GETDATE())
 GROUP BY types.type

但这再次只给出了本月预订的一种类型

使用热门查询我得到一个像这样的表

  _______________
 |TYPES   |  TOTAL|
 | DELUX  |  1    |
 | STANDARD| 3    |
 | WILD   |  0    |
 | SUPER  |  0    |

但是对于文件管理器,我得到的只是Delux作为本月唯一一个有开始/结束日期的人,我期待

       _______________
       |TYPES   |  TOTAL|
       | DELUX  |  1    |
       | STANDARD| 0    |
       | WILD   |  0    |
       | SUPER  |  0    |