计算特定属性

时间:2017-10-12 17:24:51

标签: sql-server tsql

我有以下查询,我知道这是不正确的语法

SELECT Vender as Carrier,
 count(IsPup WHERE IsPup = 1) as PU, 
 count(IsFull WHERE IsFull = 1) as FU,
 count(*) as NUM, count(IsPup)/2 + Count(IsFull) as FTE
 FROM Trailers WHERE Completed = 0 group by Vender order by NUM;

特别是count(IsPup WHERE IsPup = 1)是错误的,我搜索了各种短语,如“如何计算SQL中行的多个属性”等。 并尝试对count(IsPup) as PU, count(IsFull) as FU

等同一查询进行其他操作

我有语法正确的查询

SELECT Vender as Carrier, 
count(IsPup) as PU,
count(IsFull) as FU, 
count(*) as NUM, 
count(IsPup)/2 + Count(IsFull) as FTE 
FROM Trailers WHERE Completed = 0 group by Vender order by NUM

运行但PU,FU和NUM总是相同的值......

我正试图找到如下表格

| Carrier   | PU        | FU  |  NUM | FTE |
--------------------------------------------
| Vender1   | 2         |  1  |   3  | 2   |
| Vender2   | 0         |  4  |   4  | 4   |
| TOTAL     | 2         |  5  |   7  | 6   |     

预告片表将IsPup和IsFull作为BIT类型,因此它们为true或false(0或1) 我认为这个查询很简单,感觉我错过了一些明显的东西

如何获取每个单独财产的计数和总数? 标记的重复问题与底部的总计格式不匹配。

1 个答案:

答案 0 :(得分:2)

SELECT 
    VENDER
,   SUM(CAST(IsPUP AS INT)) AS PU
,   SUM(CAST(IsFull AS INT)) AS FU
,   COUNT(*) AS NUM
,   SUM(CAST(IsPUP AS INT)) * .5 + SUM(CAST(IsFull AS INT))
FROM Trailers
WHERE COMPLETED = 0
GROUP BY VENDER
WITH ROLLUP