Sql-Server

獲取計數(列)以及每組 中的特定行

  • January 29, 2017

我正在使用 SQL Server 2012。

我想獲取每組中的列數以及具有特定條件的行。

我想到的查詢看起來像這樣:

select count(column1), (column2 where column2 contains 'page1')
group by column1

我知道上面的查詢不正確,但我想展示一下這個想法。

樣本數據

列 1 列 2
------- --------
x1 'temp/page1_l'
x1 'temp/page2_f'
x2'temp/page2_d'
x2 'temp/page1_k'
x2'temp/page2_e'

預期產出

計數(列 1)列 2
-------------- --------------
2 '臨時/page1_l'
3 '臨時/page1_k'

我怎樣才能實現該輸出?

鑑於此範例數據:

CREATE TABLE #d ( column1 char(2), column2 varchar(32) );

INSERT #d (column1, column2) 
  VALUES ('x1',    'temp/page1_l'),
         ('x1',    'temp/page2_f'),
         ('x2',    'temp/page2_d'),
         ('x2',    'temp/page1_k'),
         ('x2',    'temp/page2_e');

解決它的一種方法是分別計算:

;WITH agg AS
(
 SELECT column1, col1count = COUNT(*)
   FROM #d 
   GROUP BY column1
)
SELECT [count(column1)] = agg.col1count, filt.column2
 FROM agg INNER JOIN #d AS filt
   ON agg.column1 = filt.column1
 WHERE filt.column2 LIKE '%page1[_]%';

或略有不同:

;WITH d AS
(
 SELECT column1, column2, 
   column1count = COUNT(*) OVER (PARTITION BY column1)
 FROM #d
)
SELECT [count(column1)] = column1count, column2 
 FROM d
 WHERE column2 LIKE '%page1[_]%';

另一個是按照 Rob 的建議:

SELECT [count(column1)] = COUNT(column1),
   column2 = MIN(CASE WHEN column2 LIKE '%page1[_]%' THEN column2 END)
 FROM #d 
 GROUP BY column1;

引用自:https://dba.stackexchange.com/questions/162547