2013-10-28 73 views
-2

我正在寫數據庫視圖中兩次使用同一列的sql查詢。在SQL查詢中使用同一列兩次

這裏是我的查詢:

SELECT ElectricityMachinePanelDetails.MachineDescription AS "Machine Name", 
     ReadingValue AS "Last Day Meter Reading" 
FROM ElectricityDailyMeterReadingDetails 
INNER JOIN ElectricityMachinePanelDetails ON ElectricityMachinePanelDetails.MachinePanelID = ElectricityDailyMeterReadingDetails.MachinePanelID 
INNER JOIN ReadingTypesDetails ON ElectricityDailyMeterReadingDetails.ReadingTypeID = ReadingTypesDetails.ReadingTypeID 
WHERE ReadingCategoryID = 'RC001' AND 
     ReadingTypesDetails.ReadingTypeID = 'RT001' 

我怎樣才能在DataGrid中使用的列名ReadingValue兩次。

回答

0

如果datagridview允許doublename im不確定,那麼您可以只使用它兩次。否則,只需給它另一個名字「Last Day Meter Reading Copy」。

Select 
ElectricityMachinePanelDetails.MachineDescription AS "Machine Name", 
ReadingValue AS "Last Day Meter Reading", 
ReadingValue AS "Last Day Meter Copy" 
from ElectricityDailyMeterReadingDetails 
INNER JOIN ElectricityMachinePanelDetails on ElectricityMachinePanelDetails.MachinePanelID = ElectricityDailyMeterReadingDetails.MachinePanelID 
INNER JOIN ReadingTypesDetails ON ElectricityDailyMeterReadingDetails.ReadingTypeID = ReadingTypesDetails.ReadingTypeID where ReadingCategoryID = 'RC001' AND ReadingTypesDetails.ReadingTypeID = 'RT001' 

在MSSQL中你不能有兩次相同的列名我想。但在MySQL中很好。

1

首先,在連接中使用別名而不是表名。所以你的查詢可以更具可讀性。

select 
    empd.MachineDescription as "Machine Name", 
    rtd.ReadingValue AS "Last Day Meter Reading" 
from ElectricityDailyMeterReadingDetails as edmrd 
    inner join ElectricityMachinePanelDetails as empd on empd.MachinePanelID = edmrd.MachinePanelID 
    inner join ReadingTypesDetails as rtd on rtd.ReadingTypeID = edmrd.ReadingTypeID 
where 
    rtd.ReadingCategoryID = 'RC001' and 
    rtd.ReadingTypesDetails.ReadingTypeID = 'RT001' 

如果你想加入ReadingTypesDetails兩次,你可以很容易地做到這一點:

select 
    empd.MachineDescription as "Machine Name", 
    rtd.ReadingValue as "Last Day Meter Reading", 
    rtd2.ReadingValue as "Another Reading" 
from ElectricityDailyMeterReadingDetails as edmrd 
    inner join ElectricityMachinePanelDetails as empd on empd.MachinePanelID = edmrd.MachinePanelID 
    inner join ReadingTypesDetails as rtd on rtd.ReadingTypeID = edmrd.ReadingTypeID 
    inner join ReadingTypesDetails as rtd2 on rtd2.ReadingTypeID = edmrd.ReadingTypeID 
where 
    rtd.ReadingCategoryID = 'RC001' and 
    rtd.ReadingTypesDetails.ReadingTypeID = 'RT001' and 
    --rtd2.ReadingCategoryID = '????' and 
    --rtd2.ReadingTypesDetails.ReadingTypeID = '????' and 
+0

它不需要加入表的兩倍。可以簡單地使用rtd.ReadingValue兩次。 –

+1

@KayNelson我假設OP知道如何使用同一個表中的值兩次,但不知道如何連接兩次同一個表。不知道爲什麼他需要兩次絕對相同的價值。 –