A. 怎样sql统计数据区间分布
select
count(case when time>=1 and time <=2 then muid end),
count(case when time>=2.1 and time <=3 then muid end),
count(case when time>=3.1 and time <=4 then muid end)
from table
B. 查询一个数据库表有多少字段的sql
这个要看你用的什么数据库,要用到系统表,不同的数据库系统表不一样。比如MS SQL可以这样写:
select count(*) from syscolumns where id = object_id('表名')
syscolumns 就是系统表
C. sql 将一个字段的数据分列显示
SQL2000不支持开窗函数row_number() ,实现这种效果可以借助存储过程。
CREATE PROCEDURE 存储过程2
AS
set nocount on
/* 创建一个临时表,利用identity 添加一个从1开始的连续标识列 */
/* x字段我设置为变长字符串型,请更改为与原始字段类型相同 */
create table #temp (id int identity,X varchar(50))
/* 将原始表中数据插入临时表 */
insert into #temp(x) select colName from tableName order by colName
/* 输出希望得到列表效果 */
/* 思路:id除4求模数根据结果将X值分别放到字段a,b,c */
/* 用(case id%4 when 1 then id + 3 when 2 then id +2 when 3 then id +1 else id end)将每4条记录标识为一组 */
/* 最后通过求分组最大值得办法得到最终列表 */
select
max(case (case id%4 when 1 then 1 when 2 then 2 when 3 then 3 else 0 end) when 1 then x else null end) as a,
max(case (case id%4 when 1 then 1 when 2 then 2 when 3 then 3 else 0 end) when 2 then x else null end) as b,
max(case (case id%4 when 1 then 1 when 2 then 2 when 3 then 3 else 0 end) when 3 then x else null end) as c,
max(case (case id%4 when 1 then 1 when 2 then 2 when 3 then 3 else 0 end) when 0 then x else null end) as d
from #temp
group by (case id%4 when 1 then id + 3 when 2 then id +2 when 3 then id +1 else id end)
set nocount off
上面代码源自下面存储过程,相对容易理解,但是由于过程里使用多一次操作查询(update)其效率也许会慢一些(但是本人未证实)
CREATE PROCEDURE 存储过程1
AS
set nocount on
create table #temp (id int identity,X nvarchar(50),idd int, flag smallint)
insert into #temp(x) select colName from tableName order by colName
update #temp set flag=case id%4 when 1 then 1 when 2 then 2 when 3 then 3 else 0 end,
idd=case id%4 when 1 then id + 3 when 2 then id +2 when 3 then id +1 else id end
select
max(case flag when 1 then x else null end) as a,
max(case flag when 2 then x else null end) as b,
max(case flag when 3 then x else null end) as c,
max(case flag when 0 then x else null end) as d
from #temp group by idd
set nocount off
D. sql server 怎么查询数据字段说明
SQL Server的注释属于扩展属性,可以从sys.extended_properties视图中查看
SELECT * FROM sys.extended_properties WHERE major_id=OBJECT_ID('WMSBASCUS')
结果是WMSBASCUS表所有列的注释信息
minor_id是列的Id,可以从sys.columns中查看表的列id
通过sys.extended_properties和sys.columns进行关联可以查看某个具体列的信息
SELECT c.name,p.value
FROM sys.extended_properties p ,sys.columns c
WHERE p.major_id=OBJECT_ID('WMSBASCUS') and c.name='CUSTNO'
and p.major_id=c.object_id and p.minor_id=c.column_id
E. SQL 单表查询按字段分类统计如何横排显示
嵌入写:即简单,又易懂
select name ,
case type when '白班' then '1' else '' end as dayjob ,
case type when '夜班' then '1' else '' end as nightjob
from work
把上面这句做为整体,嵌入到下面。
select a.name ,count(a.dayjob),count(a.nightjob) from
(
select name ,
case type when '白班' then '1' else '' end as dayjob ,
case type when '夜班' then '1' else '' end as nightjob
from work
) as a group by a.name
括号里面就是一个子查询,这样就可以达到你的要求。