为结果 table 提供列名

Providing a column name for the resultant table

我有以下查询以所需格式提取数据

select
(
    select COUNT(serialNumber) as LOTQty
    from MobileData
    where mobileName = @mobileName and model = @model and LOTQty = @lotQty
)
,(
    select COUNT(serialNumber) as FailedQty
    from MobileData
    where mobileName = @mobileName and model = @model and LOTQty = @lotQty and PreScan = 'FAIL'
)

但是当我执行查询时,它肯定会给出所需的结果,而不是列名 "LotQty""FailedQty" 它显示 (无列名)(无列名)

我也试过如下修改上面的查询,但结果仍然一样

select
(
    select [LotQty] = COUNT(serialNumber)
    ...
)
,(
    select [FailedQty] = COUNT(serialNumber) 
    ...
)

感谢任何帮助。我正在使用 sql 服务器 2008

别名必须在子查询之外

select
(
    select COUNT(serialNumber) 
    from MobileData
    where mobileName = @mobileName and model = @model and LOTQty = @lotQty
) as LOTQty
,(
    select COUNT(serialNumber)
    from MobileData
    where mobileName = @mobileName and model = @model and LOTQty = @lotQty and PreScan = 'FAIL'
)  as FailedQty

您可以使用 ALIAS 给出列名,也可以使用一个查询而不是两个子查询来获取两个计数。

试试这个:

SELECT COUNT(serialNumber) AS LOTQty, 
       SUM(CASE WHEN PreScan = 'FAIL' THEN 1 ELSE 0 END) AS FailedQty
FROM MobileData
WHERE mobileName = @mobileName AND model = @model AND LOTQty = @lotQty;