尝试获得稍微复杂的sql语句,但似乎无法使语法正确。尝试在两个不同的表中选择各种列的计数。
SELECT
SUM(ColumninTable1),
SUM(Column2inTable1),
COUNT(DISTINCT(Column3inTable1))
FROM TABLE1
这是有效的,但我不能为我的生活弄清楚如何使用什么语法添加COUNT(DISTINCT(Column1inTable2)FROM TABLE2。
答案 0 :(得分:1)
您可以采取以下几种解决方案:
取消FULL OUTER JOIN
SELECT
SUM(MYTABLE.ID) as theSum,
COUNT(DISTINCT MYTABLE.SOMEVALUE) as theCount,
COUNT(DISTINCT MYOTHERTABLE.SOMEOTHERVALUE) as theOtherCount
FROM MYTABLE
FULL OUTER JOIN MYOTHERTABLE ON 1=0
UNION
两个查询并将其他表的列保留为空
SELECT
MAX(theSum) as theSum,
MAX(theCount) as theCount,
MAX(theOtherCount) AS theOtherCount
FROM (
SELECT
SUM(ID) as theSum,
COUNT(DISTINCT SOMEVALUE) as theCount,
NULL as theOtherCount
FROM MYTABLE
UNION ALL
SELECT
NULL,
NULL,
COUNT(DISTINCT SOMEOTHERVALUE)
FROM MYOTHERTABLE
)
针对单个记录表查询'每列查询'(例如RDB$DATABASE
)
SELECT
(SELECT SUM(ID) FROM MYTABLE) as theSum,
(SELECT COUNT(DISTINCT SOMEVALUE) FROM MYTABLE) as theCount,
(SELECT COUNT(DISTINCT SOMEOTHERVALUE) FROM MYOTHERTABLE) as theOtherCount
FROM RDB$DATABASE
每张桌子的CTE +交叉加入
WITH query1 AS (
SELECT
SUM(ID) as theSum,
COUNT(DISTINCT SOMEVALUE) as theCount
FROM MYTABLE
),
query2 AS (
SELECT
COUNT(DISTINCT SOMEOTHERVALUE) as theOtherCount
FROM MYOTHERTABLE
)
SELECT
query1.theSum,
query1.theCount,
query2.theOtherCount
FROM query1
CROSS JOIN query2
可能还有一些解决方案。您可能想问自己是否值得努力想出一个(复杂的,难以理解的)单个查询来获取这些数据,这两个查询足够,更容易理解,并且在大型数据集的情况下:两个单独的查询可能会更快。
答案 1 :(得分:0)
在这种情况下,所有“count”将返回相同的值。
尝试使用子查询执行相同的操作:
Select
(Select count (*) from Table1),
(Select count (*) from table2)
from Table3