簡體   English   中英

為基於多個參數的sql查詢添加總行並提高質量

[英]Adding total row and Increasing quality for an sql query based on multiple parameters

我在Microsoft Sql Server 2008中有一張表,如下所示:

id name timelong
1  Eray  2
1  Jack  1
1  Ali   7
1  john  3
1  Roby  5
1  Mike  4
1  Josh  11

我要做的是根據用戶的多個可選參數選擇數據。 認為有4個復選框: 0-3,4-6,7-9,10-12 ,用戶可以選擇多個復選框。 僅應看到用戶選擇的那些數據,並且需要在底部添加一個TOTAL行。

我嘗試過的是在底部,但效果不佳-TOTAL行不存在。 我的問題是如何在此處添加“總計”行,還有沒有其他更專業的方法來提供此查詢。 謝謝。

declare @interval03 bit -- 0 to 3
declare @interval06 bit -- 4 to 6
declare @interval09 bit -- 7 to 9
declare @interval12 bit -- 10 to 12

Select *, sum(timelong)
From myTable
Where (@interval03=1 and timelong<4)
      or
      (@interval06=1 and timelong>3 and timelong<7)
      or
      (@interval09=1 and timelong>6 and timelong<10)
      or
      (@interval12=1 and timelong>9 and timelong<13)
group by id, name

嘗試grouping sets

Select ID, isnull(Name, 'TOTAL'), sum(timelong)
From myTable
Where (@interval03=1 and timelong <= 3)
      or
      (@interval06=1 and timelong between 4 and 6)
      or
      (@interval09=1 and timelong between 7 and 9)
      or
      (@interval12=1 and timelong >= 10)
group by grouping sets ((ID, name), ())

假設您的查詢timelong是整數,那么我也簡化了您的where

有關grouping setsrollupcube grouping sets更多信息: https : //technet.microsoft.com/zh-cn/library/bb522495(v=sql.105).aspx

嘗試這個..增加總數的另一種方法...

declare @table Table (id INT,name VARCHAR(10), timelong INT)
insert into @table (id ,name, timelong) VALUES (1,  'Eray',  2)
insert into @table (id ,name, timelong) VALUES (1  ,'Jack'  ,1)
insert into @table (id ,name, timelong) VALUES (1  ,'Ali'  , 7)
insert into @table (id ,name, timelong) VALUES (1  ,'john'  ,3)
insert into @table (id ,name, timelong) VALUES (1  ,'Roby' , 5)
insert into @table (id ,name, timelong) VALUES (1  ,'Mike'  ,4)
insert into @table (id ,name, timelong) VALUES (1  ,'Josh' ,11)

declare @interval03 bit=1 -- 0 to 3
declare @interval06 bit -- 4 to 6
declare @interval09 bit -- 7 to 9
declare @interval12 bit -- 10 to 12

DECLARE @result TABLE (ID INT,Name VARCHAR (30),TimeLong INT)

INSERT INTO @result
Select id, name, sum(timelong) timelong
From @table
Where (@interval03=1 and timelong<4)
or    (@interval06=1 and timelong>3 and timelong<7)
or    (@interval09=1 and timelong>6 and timelong<10)
or    (@interval12=1 and timelong>9 and timelong<13)
group by id, name

INSERT INTO @result
SELECT MAX(ID) +100 ID,'Total' Name,SUM(TimeLong) TimeLong
FROM @result
HAVING COUNT(*)<>0
SELECT * FROM @result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM