我有一个查询,以前在MS SQL中使用过,想在Oracle中使用。 但是,它将返回缺少的表达式。
我需要来自同一表的数据,但具有无法在同一查询中组合的不同参数。
TABLE TTT
DATE LIC ITEM QTY SU 20-01-2019 L991234 P0042 20 S002201 20-01-2019 L991234 P0042 40 S002202 20-01-2019 L991234 P0042 60 S002203 20-01-2019 L991234 P0042 80 S002204 20-01-2019 L991234 P0042 100 S002205 21-01-2019 L991245 P0069 30 S003101 21-01-2019 L991245 P0069 60 S003102 21-01-2019 L991245 P0069 90 S003103 21-01-2019 L991245 P0069 120 S003104 22-01-2019 L991256 P0042 20 S004301 22-01-2019 L991256 P0042 40 S004302 22-01-2019 L991256 P0042 60 S004303 22-01-2019 L991256 P0042 80 S004304 23-01-2019 L991264 P0069 30 S007501 23-01-2019 L991264 P0069 60 S007502 23-01-2019 L991271 P0042 20 S008801 23-01-2019 L991271 P0042 40 S008802
查询:
SELECT TA.ITEM, TA.CNT, TB.CNT
FROM (
SELECT 1 typ, DISTINCT TTT.ITEM, TTT.NO, COUNT(DISTINCT TTT.LIC)
FROM TTT
WHERE TTT.TYPE = '6' AND TTT.ITEM = 'H01234'
GROUP BY TTT.ITEM,TTT.LIC
ORDER BY TTT.ITEM, TTT.NO
) TA
INNER JOIN
(
SELECT 2 typ, DISTINCT TTT.ITEM, COUNT(DISTINCT TTT.SU)
FROM TTT
WHERE TTT.TYPE = '6' AND TTT.ITEM = = 'H01234'
GROUP BY TTT.ITEM, TTT.SU
ORDER BY TTT.ITEM
) TB ON TA.ITEM = TB.ITEM
ORDER BY TA.ITEM
预期结果
TA.ITEM TA.CNT TB.CNT P0042 3 11 P0069 2 6
答案 0 :(得分:2)
您可以更简单地完成操作,而无需联接和联合:
select item, count(distinct lic) cnt1, count(distinct su) cnt2
from ttt
group by item
结果:
ITEM CNT1 CNT2
----- ---------- ----------
P0042 3 11
P0069 2 6
答案 1 :(得分:0)
DISTINCT
应该跟随SELECT
;您有两个连续的=
在修复该问题之后,查询看起来不错(但我不知道它是否返回所需的数据):
SELECT TA.ITEM, TA.CNT, TB.CNT
FROM ( SELECT DISTINCT 1 typ, --> here
TTT.ITEM,
TTT.NO,
COUNT (DISTINCT TTT.LIC)
FROM TTT
WHERE TTT.TYPE = '6'
AND TTT.ITEM = 'H01234'
GROUP BY TTT.ITEM, TTT.LIC
ORDER BY TTT.ITEM, TTT.NO) TA
INNER JOIN ( SELECT DISTINCT 2 typ, --> here
TTT.ITEM, COUNT (DISTINCT TTT.SU)
FROM TTT
WHERE TTT.TYPE = '6'
AND TTT.ITEM = 'H01234' --> here
GROUP BY TTT.ITEM, TTT.SU
ORDER BY TTT.ITEM) TB
ON TA.FROM_ITEM = TB.FROM_ITEM
ORDER BY TA.ITEM
答案 2 :(得分:0)
可能是join子句为ON TA.ITEM = TB.ITEM
而不是ON TA.FROM_ITEM = TB.FROM_ITEM
SELECT TA.ITEM, TA.CNT, TB.CNT
FROM (
SELECT 1 typ, DISTINCT TTT.ITEM, TTT.NO, COUNT(DISTINCT TTT.LIC)
FROM TTT
WHERE TTT.TYPE = '6' AND TTT.ITEM = 'H01234'
GROUP BY TTT.ITEM,TTT.LIC
ORDER BY TTT.ITEM, TTT.NO
) TA
INNER JOIN (
SELECT 2 typ, DISTINCT TTT.ITEM, COUNT(DISTINCT TTT.SU)
FROM TTT
WHERE TTT.TYPE = '6' AND TTT.ITEM = = 'H01234'
GROUP BY TTT.ITEM, TTT.SU
ORDER BY TTT.ITEM
) TB ON TA.ITEM = TB.ITEM
ORDER BY TA.ITEM