sql按條件
① sql按條件取值,根據不同的條件來取不同的結果
select case when DATEPART(hour,采樣時間)<9 then 10
when DATEPART(hour,采樣時間)>=9 and DATEPART(hour,采樣時間)<10 then 11
else 11:30 end as time from table
② SQL按條件匯總求和
如下:
1、第一步,將示例表導入SQL語句中,見下圖,轉到下面的步驟。
③ mysql根據條件執行sql
在項目開發中,我們常常會用到根據不同條件,執行不同的sql,在mysql中可以用 IF(expr1,expr2,expr3) 來滿足這個需求。下面我給大家一個示例:
示例1:sql比較復雜
SELECT
if(dom.PLAN_NO is null,
(ifnull( ( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE 1=1 and PO_NO=pom.PO_NO and MATERIEL_CODE = pom.MATERIEL_CODE ), 0 )),
ifnull( ( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE POM_PM_CODE = pom.PM_CODE AND PLAN_NO = dpm.PLAN_NO ), 0 )
)AS tempFiled
from tableName
where 1=1
示例2:
SELECT
if(dom.PLAN_NO=1,
( SELECT sum( DELIVERY_QTY ) FROM delivery_order_materiel WHERE 1=1 and PO_NO=pom.PO_NO and MATERIEL_CODE = pom.MATERIEL_CODE ),
( SELECT sum( DELIVERY_QTY ) FROM delivery_order WHERE 1=1 AND PLAN_NO = dpm.PLAN_NO )
)AS tempFiled
from tableName
where 1=1
④ SQL按條件匯總求和
1、首先在SQL語句中中導入樣表。
⑤ sql怎麼用查詢結果作為條件進行查詢
1、查詢資料庫表的所有欄位並直接使用select語句。從資料庫表中選擇*。
⑥ SQL按條件匯總求和
select
sum(case
when
mark
=
0
then
point
else
0
end)
as
Point_0,
sum(case
when
mark
=
1
then
point
else
0
end)
as
Point_1,
Account
from
表A
group
by
Account;
***************
我從不辯解,測試log自己看:
[TEST@ORA1]
SQL>select
*
from
表A;
POINT
MARK
ACCOUNT
----------
----------
----------
20
1
John
30
0
Allen
10
1
Allen
15
1
John
20
0
Michael
25
0
John
6
rows
selected.
[TEST@ORA1]
SQL>select
sum(case
when
mark
=
0
then
point
else
0
end)
as
Point_0,
2
sum(case
when
mark
=
1
then
point
else
0
end)
as
Point_1,
3
Account
4
from
表A
5
group
by
Account;
POINT_0
POINT_1
ACCOUNT
----------
----------
----------
30
10
Allen
25
35
John
20
0
Michael
[TEST@ORA1]
SQL>
---
以上,希望對你有所幫助。
⑦ SQL 按條件 隨機 取記錄
1.select count(*),商家 from table group by 商家
2.select count(*) from table
3.select top 3 * from table order by rnd(id)
4.select top 66 * from table order by rnd(id)
3.4. access對隨機函數的支持不好,建議在程序中實現,具體思路是先取出表中所有的id值,然後存到一個數組中,然後用程序取隨機數組
5.到底是要消費筆數最多還是金額最大。兩個條件會沖突的,消費只有1筆,但也有可以金額是最大的。
6.select id,列名1,列名2,.. into newtable(列名1,列名2,...) where id in(分別寫3,4,5的條件)
7.delete table where id not in ( select min(id) from table group by id)