SQL - Group by to get sum but also return a row if the sum is 0 - sql

I have the following table:
ID BuyOrSell Total
4 B 10
4 B 11
4 S 13
4 S 29
8 B 20
9 S 23
What I am trying to do is to have sum of B and S columns for each ID and if there is not a B or S for an ID have a row with 0, so expected output would be
ID BuyOrSell Total
4 B 21
4 S 42
8 B 20
8 S 0
9 S 23
9 B 0
I have tried this and it is kind of doing what I am after but not exactly:
DECLARE #Temp Table (ID int, BuyOrSell VARCHAR(1), charge Decimal)
INSERT INTO #Temp
SELECT 4, 'B', 10 UNION ALL
SELECT 4, 'B', 11 UNION ALL
SELECT 4, 'S', 13 UNION ALL
SELECT 4, 'S', 29 UNION ALL
SELECT 8, 'B', 20 UNION ALL
SELECT 9, 'S', 23
;With Results AS
(
SELECT ID,
BuyOrSell,
SUM(charge) AS TOTAL
FROM #Temp
Group by ID, BuyOrSell
)
Select t.*,max(
case when BuyOrSell = 'B' then 'Bfound'
end) over (partition by ID) as ref
,max(
case when BuyOrSell = 'S' then 'Sfound'
end) over (partition by ID) as ref
FROM Results t;
Thanks

Try this:
;WITH CTE(ID, BuyOrSell) AS(
SELECT
ID, T.BuyOrSell
FROM #Temp
CROSS JOIN(
SELECT 'B' UNION ALL SELECT 'S'
)T(BuyOrSell)
GROUP BY ID, T.BuyOrSell
)
SELECT
C.ID,
C.BuyOrSell,
Total = ISNULL(SUM(T.charge), 0)
FROM CTE C
LEFT JOIN #Temp T
ON T.ID = C.ID
AND T.BuyOrSell = C.BuyOrSell
GROUP BY C.ID, C.BuyOrSell
ORDER BY C.ID, C.BuyOrSell

#03Usr, despite that your question has been answered, please try this:
SELECT two.ID,
two.BuyOrSell,
ISNULL (one.Total, 0) Total
FROM
(SELECT ID,
BuyOrSell,
SUM (Total) Total
FROM #Temp
GROUP BY ID, BuyOrSell) one
LEFT OUTER JOIN
(SELECT ID,
BuyOrSell
FROM #Temp
GROUP BY ID,
BuyOrSell) two
ON one.ID = two.ID
AND one.BuyOrSell = two.BuyOrSell;

Here is a solution with tricky join:
SELECT t1.ID,
v.l as BuyOrSell,
SUM(CASE WHEN t1.BuyOrSell = v.l THEN t1.charge ELSE 0 END) AS Total
FROM #Temp t1
JOIN (VALUES('B'),('S')) v(l)
ON t1.BuyOrSell = CASE WHEN EXISTS(SELECT * FROM #Temp t2
WHERE t2.ID = t1.ID AND t2.BuyOrSell <> t1.BuyOrSell)
THEN v.l ELSE t1.BuyOrSell END
GROUP BY t1.ID, v.l
ORDER BY t1.ID, v.l
Output:
ID l Total
4 B 21
4 S 42
8 B 20
8 S 0
9 B 0
9 S 23

Related

SQL Grouping by first digit from sets of record

I need your help in SQL
I have a set of records of Cost center ID below.
what I want to do is to segregate/group them by inserting column to distinguish the category.
as you can see all digits start in 7 is belong to the bold digits.
my expected out is on below image also.
You can as the below:
DECLARE #Tbl TABLE (ID INT)
INSERT INTO #Tbl
VALUES
(735121201),
(735120001),
(5442244),
(735141094),
(735141097),
(4008060),
(735117603),
(40100000),
(735142902),
(735151199),
(4010070)
;WITH TableWithRowId
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY(SELECT NULL)) RowId,
ID
FROM
#Tbl
), TempTable
AS
(
SELECT T.RowId + 1 AS RowId FROM TableWithRowId T
WHERE
LEFT(T.ID, 1) != 7
), ResultTable
AS
(
SELECT
T.RowId ,
T.ID,
DENSE_RANK() OVER (ORDER BY (SELECT TOP 1 A.RowId FROM TempTable A WHERE A.RowId > T.RowId ORDER BY A.RowId)) AS Flag
FROM TableWithRowId T
)
SELECT * FROM ResultTable
Result:
RowId ID Flag
----------- ----------- ----------
1 735121201 1
2 735120001 1
3 5442244 1
4 735141094 2
5 735141097 2
6 4008060 2
7 735117603 3
8 40100000 3
9 735142902 4
10 735151199 4
11 4010070 4
The following query is similer with NEER's
;WITH test_table(CenterID)AS(
SELECT '735121201' UNION ALL
SELECT '735120001' UNION ALL
SELECT '5442244' UNION ALL
SELECT '735141094' UNION ALL
SELECT '735141097' UNION ALL
SELECT '4008060' UNION ALL
SELECT '735117603' UNION ALL
SELECT '40100000' UNION ALL
SELECT '735142902' UNION ALL
SELECT '735151199' UNION ALL
SELECT '4010070'
),t1 AS (
SELECT *,ROW_NUMBER()OVER(ORDER BY(SELECT 1)) AS rn,CASE WHEN LEFT(t.CenterID,1)='7' THEN 1 ELSE 0 END AS isSeven
FROM test_table AS t
),t2 AS(
SELECT t1.*,ROW_NUMBER()OVER(ORDER BY t1.rn) AS toFilter
FROM t1 LEFT JOIN t1 AS pt ON pt.rn=t1.rn-1
WHERE pt.CenterID IS NULL OR (t1.isSeven=1 AND pt.isSeven=0)
)
SELECT t1.CenterID,x.toFilter FROM t1
CROSS APPLY(SELECT TOP 1 t2.toFilter FROM t2 WHERE t2.rn<=t1.rn ORDER BY rn desc) x
CenterID toFilter
--------- --------------------
735121201 1
735120001 1
5442244 1
735141094 2
735141097 2
4008060 2
735117603 3
40100000 3
735142902 4
735151199 4
4010070 4

SQL Server: how to include count in the select query with where clause?

Let's say I have this table:
id out flag
--- --- ---
1 0 1
1 1 0
1 4 0
2 0 1
2 2 0
2 2 0
3 0 1
3 2 0
3 1 0
3 4 0
I want to count the number of rows with out=(0, 2, or 4) and later display rows where flag = 1
Basically:
select id, count(where out IN(0,2,4)) as cnt where flag = 1
My desired output:
id cnt
--- ----
1 2
2 3
3 3
This query works as expected but only when I don't have "where flag = 1":
select id,sum(case when out in (0,2,4) then 1 else 0 end) over(partition by id) as cnt
from tablename
Is there a way for me to calculate sum() of something first and store it in a column, and later filter out rows using where clause? currently what's happening is that rows are being filtered out first and later sum(...) is calculated.
Any way I can rectify this?
You can use a case expression to sum only rows for an id when they have specified values for the out column.
select id,sum(case when out in (0,2,4) then 1 else 0 end) as cnt
from tablename
group by id
Edit: To include other columns when summing, use the sum window function.
select * from (select id,flag
,sum(case when out in (0,2,4) then 1 else 0 end) over(partition by id) as cnt
--include other columns as required
from tablename
) x
where flag=1
select id,count(*) as cnt
from tablename
where out in (0,2,4)
group by id
Do count for 0,2,4 OUT. And then filter them with a Inner Join or using Correlated subquery
Schema:
CREATE TABLE #TAB (ID INT, OUT_VALUE INT, FLAG INT)
INSERT INTO #TAB
SELECT 1, 0, 1
UNION ALL
SELECT 1, 1, 0
UNION ALL
SELECT 1, 4, 0
UNION ALL
SELECT 2, 0, 1
UNION ALL
SELECT 2, 2, 0
UNION ALL
SELECT 2, 2, 0
UNION ALL
SELECT 3, 0, 1
UNION ALL
SELECT 3, 2, 0
UNION ALL
SELECT 3, 1, 0
UNION ALL
SELECT 3, 4, 0
UNION ALL
SELECT 4, 4, 0
Now do select like below
INNER JOIN
SELECT T1.ID,COUNT(1) C
FROM #TAB T1
INNER JOIN
(
SELECT DISTINCT ID FROM #TAB WHERE FLAG = 1
)FLAGS ON T1.ID = FLAGS.ID
WHERE T1.OUT_VALUE IN (0,2,4)
GROUP BY T1.ID
Correlated Sub-query
SELECT ID, C FROM (
SELECT T1.ID
,COUNT(1) C
,(
SELECT DISTINCT ID
FROM #TAB T2
WHERE T1.ID = T2.ID
AND T2.FLAG = 1
) FLAG
FROM #TAB T1 WHERE T1.OUT_VALUE IN (0,2,4)
GROUP BY T1.ID
)A
WHERE A.FLAG IS NOT NULL
The result will be
+----+---+
| ID | C |
+----+---+
| 1 | 2 |
| 2 | 3 |
| 3 | 3 |
+----+---+

SQL to check for all values in column

I have the following table in Oracle DB.
ID VALUE
-----------
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
4 1
How can I select ID's which have all 3 values (1,2,3)
The simplest option is generally something like this
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select 1 id, 1 val from dual union all
3 select 1 id, 2 val from dual union all
4 select 1 id, 3 val from dual union all
5 select 2 id, 1 val from dual union all
6 select 2 id, 2 val from dual union all
7 select 3 id, 1 val from dual union all
8 select 3 id, 2 val from dual union all
9 select 3 id, 3 val from dual union all
10 select 4 id, 1 val from dual
11 )
12 select id
13 from x
14 where val in (1,2,3)
15 group by id
16* having count(distinct val) = 3
SQL> /
ID
----------
1
3
The WHERE clause identifies the values you're interested in. The HAVING clause tells you how many of those values need to exist. If you wanted all the rows that had at least 2 of the 3 values, for example, you'd change the HAVING clause to look for a COUNT of 2.
If a particular val is guaranteed to occur at most once per id, you can eliminate the distinct in the HAVING clause.
Try this:
SELECT ID
FROM TABLENAME T
WHERE EXISTS (SELECT *
FROM TABLENAME T1
WHERE T1.ID = T.ID AND T1.VALUE = '1')
AND EXISTS (SELECT *
FROM TABLENAME T2
WHERE T1.ID = T.ID AND T2.VALUE = '2')
AND EXISTS (SELECT *
FROM TABLENAME T3
WHERE T1.ID = T.ID AND T2.VALUE = '3')
or
SELECT ID
FROM TABLENAME T
WHERE (SELECT COUNT( * )
FROM (SELECT VALUE
FROM TABLENAME T1
WHERE T1.ID = T.ID
GROUP BY VALUE)) = 3;
where 3 is number of values which can be calculated by a
SELECT COUNT( * )
FROM TABLENAME T1
GROUP BY VALUE
so this will be general purpose:
SELECT ID
FROM TABLENAME T
WHERE (SELECT COUNT( * )
FROM (SELECT VALUE
FROM TABLENAME T1
WHERE T1.ID = T.ID
GROUP BY VALUE)) = (SELECT COUNT( * )
FROM TABLENAME T2
GROUP BY VALUE)
Here's an option... each expression in the HAVING clause is counting the number of values that are found equal to 1, 2, or 3. If any of these counts is less than 1, then the ID will not be returned.
http://sqlfiddle.com/#!4/00fdc/8
SELECT ID
FROM myTable
GROUP BY ID
HAVING
SUM(DECODE(VALUE, 1, 1, 0)) > 0 AND
SUM(DECODE(VALUE, 2, 1, 0)) > 0 AND
SUM(DECODE(VALUE, 3, 1, 0)) > 0
EDIT - To require value 1, and either 2 or 3:
SELECT ID
FROM myTable
GROUP BY ID
HAVING
SUM(DECODE(VALUE, 1, 1, 0)) > 0 AND
(
SUM(DECODE(VALUE, 2, 1, 0)) > 0 OR
SUM(DECODE(VALUE, 3, 1, 0)) > 0
)
select id from (select id,sum(case when value=1 then 1 else 0 end) as 'v1',
sum(case when value=2 then 1 else 0 end) as 'v2',
sum(case when value=3 then 1 else 0 end) as 'v3'
from orac group by id) as final
where v1>0 and v2>0 and v3>0
With this option you will get more than the IDs, up to your application to select the column you want:
SELECT ID,
sum(CASE WHEN VALUE = 1 THEN 1 ELSE 0 END) AS ONE,
sum(CASE WHEN VALUE = 2 THEN 1 ELSE 0 END) AS TWO,
sum(CASE WHEN VALUE = 3 THEN 1 ELSE 0 END) AS THREE
FROM MYTABLE
GROUP BY ID
HAVING ONE >= 1 AND TWO >= 1 AND THREE >= 1;
alternatively if your case is specific (only values 1, 2, 3 are possible, and no duplicate values are allowed), then you could try the following one:
SELECT ID,
count(VALUE) AS VALUECOUNT
FROM MYTABLE
GROUP BY ID
HAVING VALUECOUNT = 3;
I would take care before going that way, as you might get side effects if later you want to add additional values. But it's still worth proposing if your current case fits the restrictions given above.
And, of course, if you don't like the idea of fetching these intermediate counts, enclose the queries I gave within another select
SELECT ID FROM (
...
)

Is it possible to write a sql query that is grouped based on a running total of a column?

It would be easier to explain with an example. Suppose I wanted to get at most 5 items per group.
My input would be a table looking like this:
Item Count
A 2
A 3
A 3
B 4
B 4
B 5
C 1
And my desired output would look like this:
Item Count
A 5
A>5 3
B 4
B>5 9
C 1
An alternative output that I could also work with would be
Item Count RunningTotal
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
I can use ROW_NUMBER() to get the top X records in each group, however my requirement is to get the top X items for each group, not X records. My mind is drawing a blank as to how to do this.
declare #yourTable table (item char(1), [count] int)
insert into #yourTable
select 'A', 2 union all
select 'A', 3 union all
select 'A', 3 union all
select 'B', 4 union all
select 'B', 4 union all
select 'B', 5 union all
select 'C', 1
;with cte(item, count, row) as (
select *, row_number() over ( partition by item order by item, [count])
from #yourTable
)
select t1.Item, t1.Count, sum(t2.count) as RunningTotal from cte t1
join cte t2 on t1.item = t2.item and t2.row <= t1.row
group by t1.item, t1.count, t1.row
Result:
Item Count RunningTotal
---- ----------- ------------
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
Considering the clarifications from your comment, you should be able to produce the second kid of output from your post by running this query:
select t.Item
, t.Count
, (select sum(tt.count)
from mytable tt
where t.item=tt.item and (tt.creating_user_priority < t.creating_user_priority or
( tt.creating_user_priority = t.creating_user_priority and tt.created_date < t.createdDate))
) as RunningTotal
from mytable t
declare #yourTable table (item char(1), [count] int)
insert into #yourTable
select 'A', 2 union all
select 'A', 3 union all
select 'A', 3 union all
select 'B', 4 union all
select 'B', 4 union all
select 'B', 5 union all
select 'C', 1
;with cte(item, count, row) as (
select *, row_number() over ( partition by item order by item, [count])
from #yourTable
)
select t1.row, t1.Item, t1.Count, sum(t2.count) as RunningTotal
into #RunTotal
from cte t1
join cte t2 on t1.item = t2.item and t2.row <= t1.row
group by t1.item, t1.count, t1.row
alter table #RunTotal
add GrandTotal int
update rt
set GrandTotal = gt.Total
from #RunTotal rt
left join (
select Item, sum(Count) Total
from #RunTotal rt
group by Item) gt
on rt.Item = gt.Item
select Item, max(RunningTotal)
from #RunTotal
where RunningTotal <= 5
group by Item
union
select a.Item + '>5', total - five
from (
select Item, max(GrandTotal) total
from #RunTotal
where GrandTotal > 5
group by Item
) a
left join (
select Item, max(RunningTotal) five
from #RunTotal
where RunningTotal <= 5
group by Item
) b
on a.Item = b.Item
I've updated the accepted answer and got your desired result.
SELECT Item, SUM(Count)
FROM mytable t
GROUP BY Item
HAVING SUM(Count) <=5
UNION
SELECT Item, 5
FROM mytable t
GROUP BY Item
HAVING SUM(Count) >5
UNION
SELECT t2.Item + '>5', Sum(t2.Count) - 5
FROM mytable t2
GOUP BY Item
HAVING SUM(Count) > 5
ORDER BY 1, 2
select 'A' as Name, 2 as Cnt
into #tmp
union all select 'A',3
union all select 'A',3
union all select 'B',4
union all select 'B',4
union all select 'B',5
union all select 'C',1
select Name, case when sum(cnt) > 5 then 5 else sum(cnt) end Cnt
from #tmp
group by Name
union
select Name+'>5', sum(cnt)-5 Cnt
from #tmp
group by Name
having sum(cnt) > 5
Here is what I have so far. I know it's not complete but... this should be a good starting point.
I can get your second output by using a temp table and an update pass:
DECLARE #Data TABLE
(
ID INT IDENTITY(1,1) PRIMARY KEY
,Value VARCHAR(5)
,Number INT
,Total INT
)
INSERT INTO #Data (Value, Number) VALUES ('A',2)
INSERT INTO #Data (Value, Number) VALUES ('A',3)
INSERT INTO #Data (Value, Number) VALUES ('A',3)
INSERT INTO #Data (Value, Number) VALUES ('B',4)
INSERT INTO #Data (Value, Number) VALUES ('B',4)
INSERT INTO #Data (Value, Number) VALUES ('B',5)
INSERT INTO #Data (Value, Number) VALUES ('C',1)
DECLARE
#Value VARCHAR(5)
,#Count INT
UPDATE #Data
SET
#Count = Total = CASE WHEN Value = #Value THEN Number + #Count ELSE Number END
,#Value = Value
FROM #Data AS D
SELECT
Value
,Number
,Total
FROM #Data
There may be better ways, but this should work.

sql server : count records

I have a tableA (ID int, Match varchar, tot int)
ID Match Tot
1 123
2 123
3 12
4 12
5 4
6 12
7 8
Now, I want to calculate Tot which is total number of match exists in the table. for example 123 occured twice, 12 exist thrice and so on. Also note that I want the count only at first match. here is the expected result.:
ID Match Tot
1 123 2
2 123
3 12 3
4 12
5 4 1
6 12
7 8 1
Another case:
ID Match Count Tot
1 123 2
2 123 1
3 12 10
4 12 10
5 4 3
6 12 5
7 8 7
Now I want to add the count for the same match. expected result:
ID Match Count Tot
1 123 2 3
2 123 1
3 12 10 25
4 12 10
5 4 3 3
6 12 5
7 8 7 7
Thanks
WITH tableA(ID, Match) AS
(
SELECT 1,123 UNION ALL
SELECT 2,123 UNION ALL
SELECT 3,12 UNION ALL
SELECT 4,12 UNION ALL
SELECT 5,4 UNION ALL
SELECT 6,12 UNION ALL
SELECT 7,8
)
SELECT *,
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY Match ORDER BY ID) = 1
THEN COUNT(*) OVER (PARTITION BY Match)
END AS Tot
FROM tableA
ORDER BY ID
SELECT match, COUNT(match ) as Tot
FROM tableA
GROUP BY match
Solution 1:
DECLARE #MyTable TABLE
(
ID INT PRIMARY KEY
,Match VARCHAR(10) NOT NULL
,Tot INT NULL
);
INSERT #MyTable(ID, Match)
SELECT 1, 123
UNION ALL
SELECT 2, 123
UNION ALL
SELECT 3, 12
UNION ALL
SELECT 4, 12
UNION ALL
SELECT 5, 4
UNION ALL
SELECT 6, 12
UNION ALL
SELECT 7, 8;
--SELECT
SELECT *
,CASE
WHEN ROW_NUMBER()OVER(PARTITION BY a.Match ORDER BY a.ID ASC)=1
THEN COUNT(*)OVER(PARTITION BY a.Match)
END TotCalculated
FROM #MyTable a;
--UPDATE
WITH MyCTE
AS
(
SELECT a.Tot
,CASE
WHEN ROW_NUMBER()OVER(PARTITION BY a.Match ORDER BY a.ID ASC)=1
THEN COUNT(*)OVER(PARTITION BY a.Match)
END TotCalculated
FROM #MyTable a
)
UPDATE MyCTE
SET Tot = TotCalculated;
SELECT *
FROM #MyTable;
Solution 2:
UPDATE #MyTable
SET Tot = NULL;
SELECT x.ID, y.Num
FROM
(
SELECT b.Match, MIN(b.ID) ID
FROM #MyTable b
GROUP BY b.Match
) x INNER JOIN
(
SELECT a.Match, COUNT(*) AS Num
FROM #MyTable a
GROUP BY a.Match
) y ON x.Match = y.Match
ORDER BY x.ID
UPDATE #MyTable
SET Tot = t.Num
FROM #MyTable z
INNER JOIN
(
SELECT x.ID, y.Num
FROM
(
SELECT b.Match, MIN(b.ID) ID
FROM #MyTable b
GROUP BY b.Match
) x INNER JOIN
(
SELECT a.Match, COUNT(*) AS Num
FROM #MyTable a
GROUP BY a.Match
) y ON x.Match = y.Match
) t ON z.ID = t.ID;
SELECT *
FROM #MyTable;