2013-10-05 73 views
0

我試圖從一個表中匹配2nd表中的另一列的列的記錄數。然後我需要它所選的另一列的總值。從2個表中選擇並獲得總計數

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」。

回答

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 
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 

每個選擇提供了新的小桌子,從

選擇正確的語法取決於你的數據庫

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