为结果表提供列名

时间:2015-01-07 07:01:55

标签: sql sql-server sql-server-2008 select alias

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

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 server 2008

2 个答案:

答案 0 :(得分:3)

您可以使用 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;

答案 1 :(得分:2)

别名必须在子查询之外

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