需要帮助设计SQL语句

时间:2011-08-02 16:19:24

标签: sql oracle

无论如何,我都不是SQL大师,而且我很难绕过如何进行某个SQL查询。

我有三个Oracle数据库表,MBRHISTDETL,LOCINFODETL和METERCHGDETL。从MBRHISTDETL我将得到以下字段:MBRSEP,LOCATION,BILLTYPE,BILLMOYR,KWH。从LOCINFODETL(LOCATION是关键)我将得到DIST,CYCLE,ADDR1。从METERCHGDETL(MBRSEP是关键)我会得到METER。

到目前为止,使用下面的查询,我能够从MBRHISTDETL和LOCINFODETL获取所需的所有信息。但是,我现在还不知道如何将下一个表METERCHRDETL添加到查询语句中。有人可以帮我解决这个问题吗?

到目前为止,这是我的查询:

SELECT LOCINFODETL.LOCATION AS L.LOCATION, 
    LOCINFODETL.DIST, LOCINFODETL.CYCLE,
    LOCINFODETL.ADDR1, MBRHISTDETL.MBRSEP, 
    MBRHISTDETL.LOCATION AS M.LOCATION, 
    MBRHISTDETL.BILLTYPE, MBRHISTDETL.BILLMOYR, 
    MBRHISTDETL.KWH
FROM MBRHISTDETL 
    INNER JOIN L.LOCINFODETL ON H.MBRHISTDETL.LOCATION = L.LOCATION
WHERE MBRHISTDETL.BILLTYPE = '09' 
  AND CAV_MBRHISTDETL.BILLMOYR <> '9999' 
  AND SUBSTR(LOCINFODETL.CYCLE,0,2) = '04' 
  AND LOCINFODETL.DIST = '16' 

2 个答案:

答案 0 :(得分:3)

这应该让你开始 - 但你需要知道哪个字段链接你的M表。

另外 - 只是一个样式提示 - 如果你是第一次尝试从sql中理解的话 - 如果你将它格式化得更加直观,那么你将能够更轻松地证明你的sql 。我的风格可能不是最好的,但你可以看看它是否让你更容易阅读。

SELECT
   L.LOCATION AS L_LOCATION, 
   L.DIST, 
   L.CYCLE,
   L.ADDR1, 
   H.MBRSEP, 
   H.LOCATION AS H_LOCATION, 
   H.BILLTYPE, 
   H.BILLMOYR, 
   H.KWH,
   M.METER
FROM 
      MBRHISTDETL H
   INNER JOIN 
      LOCINFODETL L 
   ON 
      H.LOCATION = L.LOCATION
   INNER JOIN
      METERCHRDETL M
   ON M.___KEY___ = H.___KEY___ -- or perhaps L.___KEY___
WHERE 
       H.BILLTYPE = '09' 
   AND H.BILLMOYR <> '9999' 
   AND SUBSTR(L.CYCLE,0,2) = '04' 
   AND L.DIST = '16' 

答案 1 :(得分:0)

这样的东西应该有用,虽然我不是你正在使用的前缀的100%。

SELECT LOCINFODETL.LOCATION AS L.LOCATION, 
    LOCINFODETL.DIST, LOCINFODETL.CYCLE,
    LOCINFODETL.ADDR1, MBRHISTDETL.MBRSEP, 
    MBRHISTDETL.LOCATION AS M.LOCATION, 
    MBRHISTDETL.BILLTYPE, MBRHISTDETL.BILLMOYR, 
    MBRHISTDETL.KWH, METERCHGDETL.METER
FROM MBRHISTDETL 
    INNER JOIN L.LOCINFODETL ON H.MBRHISTDETL.LOCATION = L.LOCATION
    INNER JOIN METERCHGDETL ON H.MBRHISTDETL.MBRSEP = METERCHGDETL.MBRSEP 
WHERE MBRHISTDETL.BILLTYPE = '09' 
  AND CAV_MBRHISTDETL.BILLMOYR <> '9999' 
  AND SUBSTR(LOCINFODETL.CYCLE,0,2) = '04' 
  AND LOCINFODETL.DIST = '16'