是否可以返回行数和行数?

时间:2014-04-03 01:11:52

标签: sql-server tsql

假设我有这个查询

SELECT T1.Col1,
       (
         SELECT TOP 1 T3.Col1
         FROM Table3 T3
         INNER JOIN Table4 T4
         ON T3.Col3 = T4.Col1
         WHERE T4.Col2 = T1.Col1
       )
       T1.Col2,
       T1.Col3,
       T2.Col1
       T2.Col2
       FROM Table1 T1
       LEFT JOIN Table2 T2
       ON T1.Col1 = T2.Col2 

到目前为止,SELECT TOP 1返回一行。有没有办法返回计数?我想返回类似AA_123_BB_4567 (3).的内容,其中3是列数,因为我只能显示第一行。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

如果我正确地理解了这个问题,你想做这样的事情:

SELECT T1.Col1,
       (
         SELECT TOP 1 T3.Col1
         FROM Table3 T3
         INNER JOIN Table4 T4
         ON T3.Col3 = T4.Col1
         WHERE T4.Col2 = T1.Col1
       ) as the_top_1,
       (
         SELECT count(1)
         FROM Table3 T3
         INNER JOIN Table4 T4
         ON T3.Col3 = T4.Col1
         WHERE T4.Col2 = T1.Col1
       ) as the_count,
       T1.Col2,
       T1.Col3,
       T2.Col1
       T2.Col2
       FROM Table1 T1
       LEFT JOIN Table2 T2
       ON T1.Col1 = T2.Col2 

或者这个:

SELECT 
    T1.Col1,
    T1.Col2,
    T1.Col3,
    T2.Col1,
    T2.Col2,
    x.top_1,
    x.the_count
FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.Col1 = T2.Col2 
left join (
    SELECT
        T4.col2,
        min(T3.Col1) as top_1,
        COUNT(1) as the_count
    FROM Table3 T3
    INNER JOIN Table4 T4 ON T3.Col3 = T4.Col1
    group by T4.col2
) x on x.Col2 = T1.Col1