gpt4 book ai didi

sql-server - 如何在mssql中计算具有特定数据的行数

转载 作者:行者123 更新时间:2023-12-03 07:55:48 30 4
gpt4 key购买 nike

我有下表:

项目:

ID     Type     StockExists  
01 Cellphone T
02 Cellphone F
03 Apparrel T

我要 count the number of items与现有股票,即行数 StockExists='T' .我正在执行查询;
Select count(StockExists) 
From [Items] where StockExists='T'

但它总是返回 1. 正确的做法是什么?

编辑:

另外,如何执行另一个这样的 Count 操作并将它们添加到一行中,例如,
Select count(StockExists) 
From [Items] where StockExists='T'` and `Select count(Type)
From [Items] where Type='Cellphone'` ?

最佳答案

SELECT 
COUNT(*) As ExistCount
FROM
dbo.Items
WHERE
StockExists='T'

所以你的查询应该有效。

结果:
EXISTCOUNT
2

Demo

更新

How to perform another such Count operation and add them together in one row, for example, Select count(StockExists) From [Items] where StockExists='T' and Select count(Type) From [Items] where Type='Cellphone' ?



您可以使用 SUMCASE :
SELECT 
ExistCount = SUM(CASE WHEN StockExists='T' THEN 1 ELSE 0 END) ,
CellphoneCount = SUM(CASE WHEN Type='Cellphone' THEN 1 ELSE 0 END)
FROM
dbo.Items

结果:
EXISTCOUNT    CELLPHONECOUNT
2 2

Demo

关于sql-server - 如何在mssql中计算具有特定数据的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14751787/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com