[英]Inserting a count of a total into a temp table with a conditional statement?
我有一些看起來像這樣的數據:
P D
1 0
1 0
.63 1
.72 1
etc...
現在,我有了一個臨時表,該表需要3個值,並且我想使用第一個表來創建該表,該表根據某些條件保存這些值的總數。
這是一個執行此操作的語句,但是它只能運行一次,我對SQL不太滿意,但是有人可以告訴我如何動態地完成這樣的事情嗎?
INSERT INTO #distribution values(
(SELECT count(P)
FROM myTable
WHERE P > 0.90 AND D = 0), 1, 1)
臨時表中的最后2個值將根據要檢查的條件而變化。
例如,這是我的另一個條件:
WHERE (P BETWEEN 0.80 AND 0.90) AND (D BETWEEN .01 AND .25), 1,2
我在想我需要一個案例聲明,但是想不出如何做到這一點。
編輯 :在某些情況下,其他2列也會更改。
例如:
WHERE (P > 0.90) AND (D BETWEEN .01 AND .25),2,1
如果我理解的話,不確定100%,但我認為您想要以下內容:
INSERT INTO #distribution
SELECT COUNT(1), 1, 1
FROM MyTable
WHERE P > 0.90 AND D = 0
UNION ALL
SELECT COUNT(1), 1, 2
FROM MyTable
WHERE (P BETWEEN 0.80 AND 0.90) AND (D BETWEEN .01 AND .25)
或者,您可以執行以下操作:
SELECT b.TypeCount, a.VALUE1, a.VALUE2
FROM
(SELECT 1 AS TypeId, 1 AS VALUE1, 1 AS VALUE2
UNION ALL
SELECT 2, 1, 2) ValueTable
JOIN (SELECT CASE WHEN P > 0.90 AND D = 0 THEN 1
WHEN (P BETWEEN 0.80 AND 0.90) AND (D BETWEEN .01 AND .25) THEN 2 END AS TypeId,
COUNT(1) TypeCount
FROM MyTable
GROUP BY SELECT CASE WHEN P > 0.90 AND D = 0 THEN 1
WHEN (P BETWEEN 0.80 AND 0.90) AND (D BETWEEN .01 AND .25) THEN 2 END) AS Data
ON Data.TypeId = ValueTable.TypeId
考慮到這是結構化編程而不是事務處理的領域,SQL並不是很擅長。 就像您提到的那樣,考慮到我會提出一份案情陳述。 像這樣:
insert into #distribution
select count(*),
case t.conditions
when 1 then 1
when 2 then 1
[more conditions...]
end,
case t.conditions
when 1 then 1
when 2 then 2
[more conditions...]
end
from (
select case
when P > 0.90 and D = 0 then 1
when P >= 0.80 and P <= 0.90 and D >= .01 and D <= .25 then 2
[more conditions...]
end as conditions
from myTable
) as t
group by conditions
我認為這是您想要的:
insert into #distribution(col1, col2, col3)
select count(*), 1, grp
from (select (case when P > 0.90 and D = 0 then 1
when P >= 0.80 and P <= 0.90 and D >= .01 and D <= .25 then 2
end) as grp
from myTable
) as t
where grp is not null
group by grp;
注意:您應該列出insert
的列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.