最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。
所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。
1、SQLServer 把表的挨着的四条数据合并到一起
http://bbs.csdn.net/topics/390735343
数据:
a a
b b
c c
d d
e e
f f
g g
h h
i i
我的方法:
-
--drop table t
-
-
create
table t(
name
varchar(
10),pass
varchar(
10))
-
-
insert
into t
-
select
'a',
'a'
union all
-
select
'b',
'b'
union all
-
select
'c',
'c'
union all
-
select
'd',
'd'
union all
-
select
'e',
'e'
union all
-
select
'f',
'f'
union all
-
select
'g',
'g'
union all
-
select
'h',
'h'
union all
-
select
'i',
'i'
-
go
-
-
-
select
MAX(
case
when rn =
1
then
name
else
null
end)
name,
-
MAX(
case
when rn =
1
then pass
else
null
end) pass,
-
MAX(
case
when rn =
2
then
name
else
null
end)
name,
-
MAX(
case
when rn =
2
then pass
else
null
end) pass,
-
MAX(
case
when rn =
3
then
name
else
null
end)
name,
-
MAX(
case
when rn =
3
then pass
else
null
end) pass,
-
MAX(
case
when rn =
4
then
name
else
null
end)
name,
-
MAX(
case
when rn =
4
then pass
else
null
end) pass
-
from
-
(
-
select *,
-
ROW_NUMBER()
over(
partition
by
rownum
order
by
getdate()) rn
-
from
-
(
-
select *,
-
(ROW_NUMBER()
over(
order
by
getdate())
-1) /
4
rownum
-
from t
-
)t
-
)t
-
group
by
rownum
-
/*
-
name pass name pass name pass name pass
-
a a b b c c d d
-
e e f f g g h h
-
i i NULL NULL NULL NULL NULL NULL
-
*/
2、怎么用简单的sql语句记流水?
http://bbs.csdn.net/topics/390674508
有一个流水表TF,字段有ID,FirstQuantity,ChangeQuantity,FinalQuantity。ID表示物品,后面几个表示期初数量,变化数量,最终数量。
假设表TF现在是空
有一张变动表TC,字段有ID,Quantity。表示某物品的数量。里面会有重复。内容如下:
ID Quantity
1 10
1 20
1 30
那么当我把TC的数据加入到TF后,TF的内容应该如下:
-
ID FirstQuantity ChangeQuantity FinalQuantity
-
1 0 10 10
-
1 10 20 30
-
1 30 30 60
这个功能,用编程的方法很好解决,就是一个一个循环写入,但是效率太慢了。
那么能不能用一条sql语句就搞定呢?
我的方法:
-
create
table tc(
ID
int, Quantity
int)
-
-
insert
into tc
-
select
1 ,
10
union all
-
select
1 ,
20
union all
-
select
1 ,
30
-
go
-
-
;with t
-
as
-
(
-
select *,
-
ROW_NUMBER()
over(
partition
by
id
order
by @@servername)
rownum
-
from tc
-
)
-
-
-
select
ID,
-
FirstQuantity,
-
ChangeQuantity,
-
FirstQuantity+ChangeQuantity
as inalQuantity
-
from
-
(
-
select
ID,
-
case
when
rownum =
1
then
0
-
else (
select
SUM(Quantity)
from t t2
-
where t2.ID = t1.id
and t2.rownum < t1.rownum)
-
end
as FirstQuantity,
-
Quantity
as ChangeQuantity
-
from t t1
-
)tt
-
/*
-
ID FirstQuantity ChangeQuantity inalQuantity
-
1 0 10 10
-
1 10 20 30
-
1 30 30 60
-
*/