我试图获取结果中的总行数,但我的查询仅显示记录,但不对它们进行计数。
我使用了count函数,但是没有用。
SELECT BOM.STYLE_ID,
BOM.SEASON_ID,
(CASE WHEN bom.Content_class = upper('ART') THEN
(CASE WHEN bom.Mat_ref_id IN (SELECT mat_ref_id
FROM iplexmat_material_parm
WHERE artwrk_type = 'EMB') THEN count(Mat_ref_id)
ELSE '' END)
END) AS EMBRO,
(CASE
WHEN bom.Mat_ref_id IN
(SELECT mat_ref_id
FROM iplexmat_material_parm
WHERE artwrk_type = 'PRT') THEN count(Mat_ref_id)
ELSE 0
END) AS PRINTINGG
FROM IPLEXSTY_AD_BOM_DTL BOM
WHERE CONTENT_CLASS = 'ART'
AND Style_id = 'S1407LHFFR029L'
GROUP BY BOM.STYLE_ID,
bom.Content_class,
BOM.SEASON_ID,
Mat_ref_id;
当查询中的给定参数返回true时,我想要的是在查询中显示的总行数。因此,结果应该只有一行。空值不应包括在内。
答案 0 :(得分:1)
可以使用cte
或不使用cte-COUNT(1) OVER()
来实现。
这种使用cte的方法:
;with cte as
(
SELECT BOM.STYLE_ID, BOM.SEASON_ID,
(CASE WHEN bom.Content_class = upper('ART') THEN
(case when bom.Mat_ref_id in (select mat_ref_id from iplexmat_material_parm where artwrk_type = 'EMB') then
count(Mat_ref_id) ELSE '' END)end) AS EMBRO,
(case when bom.Mat_ref_id in (select mat_ref_id from iplexmat_material_parm where artwrk_type = 'PRT') THEN
count(Mat_ref_id) ELSE 0 END) AS PRINTINGG
FROM IPLEXSTY_AD_BOM_DTL BOM
WHERE CONTENT_CLASS = 'ART' AND Style_id = 'S1407LHFFR029L'
GROUP BY BOM.STYLE_ID, bom.Content_class,BOM.SEASON_ID,Mat_ref_id
)
SELECT
*
, (SELECT COUNT(1) FROM cte) -- Number of rows
FROM cte
一个简单的例子:
DECLARE @TestTable TABLE
(
Col1 VARCHAR(10),
Col2 INT,
Col3 INT
)
INSERT INTO @TestTable
(
Col1,
Col2,
Col3
)
VALUES
('A', 10, 20)
,('A', 11, 30)
,('A', 12, 40)
,('A', 12, 60)
-- Without cte:
SELECT
*
, COUNT(1) OVER() OverallRowCount
FROM @TestTable tt
更新(感谢Panagiotis Kanavos)。这种没有cte的方法:
SELECT
BOM.STYLE_ID
, BOM.SEASON_ID
, (CASE WHEN bom.Content_class = upper('ART') THEN
(case when bom.Mat_ref_id in (select mat_ref_id from iplexmat_material_parm where artwrk_type = 'EMB')
then count(Mat_ref_id) ELSE '' END)end) AS EMBRO
, (case when bom.Mat_ref_id in (select mat_ref_id from iplexmat_material_parm
where artwrk_type = 'PRT') THEN
count(Mat_ref_id) ELSE 0 END) AS PRINTINGG
, COUNT(1) OVER() OverallRowCount
FROM IPLEXSTY_AD_BOM_DTL BOM
WHERE CONTENT_CLASS = 'ART' AND Style_id = 'S1407LHFFR029L'
GROUP BY BOM.STYLE_ID, bom.Content_class,BOM.SEASON_ID,Mat_ref_id