我想选择3个表,代码是777
Table 1
Employee code Company Name
001 a
002 b
Table 2
Employee code Voucher NO Date Amount
001 123 12-4-14 100
001 456 2-5-14 500
002 789 3 -7 14 300
Table 3
Voucher No Tax amt code
123 50 777
789 100 888
输出应为
Company Name Employee code Voucher No Date Amount Tax amt code
a 001 123 12-4-14 100 50 777
a 001 456 2-5-14 500 null null
但应用查询时有重复的行
SELECT DISTINCT
table1.COMPANY_NAME,
table2.EMPLOYEE_CODE,
table2.VOUCHER_NO,
table2.DATE,
table2.AMOUNT,
table3.TAX_AMT,
table3.CODE
FROM table2
INNER JOIN table1 ON (table2.EMPLOYEE_CODE = table1.EMPLOYEE_CODE)
INNER JOIN table3 ON (table2.VOUCHER_NO = table3.VOUCHER_NO )
WHERE table3.CODE = '777'
以上查询的输出
Company Name Employee code Voucher No Date Amount Tax amt code
a 001 123 12-4-14 100 50 777
a 001 456 2-5-14 500 **50 777**
我尝试使用DISTINCT但是因为没有用。请帮助我查询问题。
答案 0 :(得分:0)
试试这个:
SELECT
table1.COMPANY_NAME,
table2.EMPLOYEE_CODE,
table2.VOUCHER_NO,
table2.DATE,
table2.AMOUNT,
table3.TAX_AMT,
table3.CODE
FROM table1
INNER JOIN table2 ON (table2.EMPLOYEE_CODE = table1.EMPLOYEE_CODE)
LEFT JOIN table3 ON (table2.VOUCHER_NO = table3.VOUCHER_NO )
HAVING
(table3.CODE = '777' OR table3.CODE IS NULL)
如果您需要其他内容,或者您有特定问题,请给我留言。
答案 1 :(得分:0)
由于您使用WHERE
语句进行过滤,因此SQL命令不会生成您的示例输出。
如果只需要输出777
代码,则应使用条件而不是WHERE的LEFT JOIN
.....
FROM table2
INNER JOIN table1 ON (table2.EMPLOYEE_CODE = table1.EMPLOYEE_CODE)
LEFT JOIN table3 ON (table2.VOUCHER_NO = table3.VOUCHER_NO )
AND (table3.CODE = '777')
答案 2 :(得分:0)
您的输出中的第二行可能是因为它在table2中具有相同的EMPLOYEE_CODE
,所以我认为这可能是您想要的查询:
SELECT
table1.COMPANY_NAME,
table2.EMPLOYEE_CODE,
table2.VOUCHER_NO,
table2.DATE,
table2.AMOUNT,
table3.TAX_AMT,
table3.CODE
FROM table2
INNER JOIN table1 ON (table2.EMPLOYEE_CODE = table1.EMPLOYEE_CODE)
LEFT JOIN table3 ON (table2.VOUCHER_NO = table3.VOUCHER_NO )
WHERE table1.EMPLOYEE_CODE IN
(SELECT table2.EMPLOYEE_CODE
FROM table2 INNER JOIN table3 ON (table2.VOUCHER_NO = table3.VOUCHER_NO)
WHERE table3.code = '777')