在SQL查询中使用相同的列两次

时间:2013-10-28 12:14:26

标签: mysql sql sql-server datagrid

我正在编写SQL查询,我希望在datagrid视图中使用相同的列两次。

这是我的问题:

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' 

如何在数据网格中使用列名ReadingValue两次。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果datagridview允许doublename我不确定,你可以使用它两次。否则只需给它另一个名字“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中很好。