我是SQL新手,我坚持使用的东西肯定很容易解决,但却让我发疯。我有一个巨大的AS400 txt数据导出,我需要从中获取一些数据。使用单个查询,我得到正确的数字,但我想知道是否有一种方法可以编写一个查询,该查询给出一个包含四个结果的表,每个结果都在一列中。
以下是四个查询:
SELECT COUNT([DATA1]) FROM (SELECT DISTINCT [DATA1] FROM STATUS);
SELECT COUNT([DATA2]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3] FROM STATUS);
SELECT COUNT([DATA3]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3], [TAL] FROM STATUS);
SELECT SUM([UNITS]) AS TOTAL FROM STATUS;
尝试使用UNION ALL,但所有结果都显示在同一列中。
有办法做到这一点吗?在一个查询中获取四个数字,每个结果都在不同的列中。
非常感谢你的帮助和时间。
答案 0 :(得分:0)
这可能是你想要的:
SELECT
(SELECT COUNT([DATA1]) FROM (SELECT DISTINCT [DATA1] FROM STATUS)) [DATA1],
(SELECT COUNT([DATA2]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3] FROM STATUS)) [DATA2],
(SELECT COUNT([DATA3]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3], [TAL] FROM STATUS)) [DATA3],
(SELECT SUM([UNITS]) AS TOTAL FROM STATUS) [UNITS];
对于所有子查询,可能还有进一步改进的空间,但是使用此查询,您应该将所有COUNT
结果放在一行的不同列中。
答案 1 :(得分:0)
我正在检查SQL Server 2008,我注意到对于带有count(Data2)和Count(Data3)的查询,我们可能需要为内部select选择一个别名,以获得正确的结果。
SELECT DATA1_CNT = (SELECT COUNT([DATA1]) FROM (SELECT DISTINCT [DATA1] FROM STATUS)),
DATA2_CNT =(SELECT COUNT([DATA2]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3] FROM STATUS) d1),
DATA3_CNT = (SELECT COUNT([DATA3]) FROM (SELECT DISTINCT [DATA1], [DATA2], [DATA3], [TAL] FROM STATUS) d2),
UNITS_SUM = (SELECT SUM([UNITS]) AS TOTAL FROM STATUS)