从2个表中选择并获得计数总数

时间:2013-10-05 20:11:11

标签: sql sql-server-2008

我正在尝试从一个表中获取记录数,其中列与2nd表中的另一列匹配。然后我需要它所选择的另一列的总值。

SELECT
  h.holiday_id,
  h.holiday_name,
  CONVERT(Money,b.total_balance) AS total_balance,
  b.booking_status_id,
  Sum(CONVERT(Money,b.total_balance)) AS total_balance,
  Count(*) AS record_count
FROM
  [arend].[aren1002].[HOLIDAY_REF] AS h,
  [arend].[aren1002].[BOOKING] AS b
LEFT JOIN
  [arend].[aren1002].[BOOKING]
ON
  h.holiday_id=booking.holiday_id
WHERE
  b.booking_status_id = '330' AND h.holiday_id = b.holiday_id
ORDER BY h.holiday_id

Table 1 HOLIDAY_REF
holiday_id | holiday_name
1 | Italy
2 | Russia
3 | Spain

Table 2 BOOKING
holiday_id | booking_status_id | total_balance
1 | 330 | 2500
3 | 330 | 1500
1 | 330 | 1750
2 | 330 | 1240
2 | 330 | 5600

Results:
Holiday_id | holiday_name | total_balance | record_count
1 | Italy | 4250 | 2
2 | Russia | 6840 | 2
3 | Spain | 1500 | 1

不确定我是否正确行事。

更新:我已经更新了sql命令以反映我所处的位置,我现在收到一个错误: 无法绑定多部分标识符“h.holiday_id”。

3 个答案:

答案 0 :(得分:1)

我真的不明白为什么需要两次加入一张桌子。

如何使用GROUP BY,它会为您提供SUMCOUNT的结果。

这样的东西
SELECT
  h.holiday_id,
  Sum(CONVERT(Money,b.total_balance)) AS total_balance,
  Count(*) AS record_count
FROM
  [arend].[aren1002].[HOLIDAY_REF] AS h,
  [arend].[aren1002].[BOOKING] AS b
WHERE
  b.booking_status_id = '330' AND h.holiday_id = b.holiday_id
GROUP BY h.holiday_id
ORDER BY h.holiday_id

答案 1 :(得分:1)

我会确保你将total_balance存储为金钱,这样你就不必在显示数据时进行转换。

即使你正在使用左连接,通过检查booking_status_id ='330'它将排除Holiday_Ref中的所有条目,而没有状态为'330'的相应预订条目。如果这是期望的行为,您可以使其更明确并使用内部联接。

在当前查询中,您选择的列数多于所需的结果集。这就是我的建议:

select
    holiday_ref.holiday_id
   ,holiday_ref.holiday_name
   ,sum(booking.total_balance) as total_balance
   ,count(1) as record_count
from
    holiday_ref
inner join
    booking 
 on holiday_ref.holiday_id = booking.holiday_id
where
    booking.booking_status_id = '330'
group by
    holiday_ref.holiday_id
   ,holiday_ref.holiday_name

答案 2 :(得分:0)

SQL与结果一起使用:

select * from HOLIDAY_REF 

给出上面的表格

select * from BOOKING 

给出了上面的另一张表

select * from HOLIDAY_REF a, BOOKING b  where a.holiday=b.holiday give a combined table

所以 - 这就是你的伎俩

select * from ( 
    select * from HOLIDAY_REF a, BOOKING b  where a.holiday=b.holiday gove a combined table
)

给出相同的结果集,但是..

你可以做点什么

 select *  from ( 
    select * from HOLIDAY_REF a, BOOKING b  where a.holiday=b.holiday gove a combined table
) where b.booking_status_id = '330' and a..... what ever 

每个选择都会提供新的小表以供选择

正确的语法取决于您的数据库