Here below some sample 3 data, using PostgreSQL and rails
Stock
id: 42324
name: 'n1'
stock_items
id: 57889359
stock_id: 42324
check_id: 14123
turn: 5
mock_id: 57889357
id: 57889360
stock_id: 42324
check_id: 14141
turn: 3
mock_id: 0
Stock
id: 42325
name: 'n1'
stock_items
id: 57889361
stock_id: 42325
check_id: 19499
turn: 5
mock_id: 57889359
id: 57889362
stock_id: 42325
check_id: 19500
turn: 3
mock_id: 0
Here i have stock table and stock_items table i am trying to take the result like
if mock_id is 0 then get the check_id else other check_id whose mock_id is not zero.
So i tried one query
SELECT
check_id1,
CASE
WHEN stock_items.mock_id = 0 THEN stock_items.check_id
ELSE stock_items.check_id
END as check_id2
FROM
stock_items
INNER JOIN stocks on stocks.id = stock_items.stock_id ;
but the above query fails, but i need it like below, any suggestions?
check_id1 (mock_id=0) | check_id2 (mock_id !=0)
----------------------+-----------------------
14141 | 14123
19500 | 19499
CASE statement doesn't work like you think. You can read it here https://www.postgresql.org/docs/8.1/static/functions-conditional.html
Your query shoud look like this
SELECT s.check_id1, s2.check_id1 FROM stock_items s, (SELECT * FROM stock_items WHERE mock_id <> 0) s2 WHERE s.stock_id = s2.stock_id
What you're trying to do is basically a PIVOT. You should actually use two CASE, within an aggregation function, and having a GROUP BY (and an ORDER BY to get the order you gave):
SELECT
stock_id,
max(CASE when mock_id =0 then check_id END) AS "check_id1 (mock_id=0)",
max(CASE when mock_id<>0 then check_id END) AS "check_id2 (mock_id!=0)"
FROM
stock_items
INNER JOIN stocks on stocks.id = stock_items.stock_id
GROUP BY
stock_id
ORDER BY
stock_id;
stock_id | check_id1 (mock_id=0) | check_id2 (mock_id!=0)
-------: | --------------------: | ---------------------:
42324 | 14141 | 14123
42325 | 19500 | 19499
NOTE: I've added the stock_id so that the result is easier to understand. You can omit it if you don't actually want it in your response.
You can check all the setup and test it at dbfiddle here
UPDATE
As per comments
SELECT
stock_id,
-- This will get rid of the null in array_agg
ARRAY(SELECT
e
FROM
unnest(all_check_ids_with_mock_id_0) AS e
WHERE
e IS NOT NULL
) AS all_check_ids_with_mock_id_0,
ARRAY(SELECT
e
FROM
unnest(all_check_ids_with_mock_id_non_0) AS e
WHERE
e IS NOT NULL
) AS all_check_ids_with_mock_id_non_0
FROM
(
SELECT
stock_id,
array_agg(CASE WHEN mock_id =0 THEN check_id END) AS all_check_ids_with_mock_id_0,
array_agg(CASE WHEN mock_id<>0 THEN check_id END) AS all_check_ids_with_mock_id_non_0
FROM
stock_items
INNER JOIN stocks on stocks.id = stock_items.stock_id
GROUP BY
stock_id
) AS q0
ORDER BY
stock_id;
stock_id | all_check_ids_with_mock_id_0 | all_check_ids_with_mock_id_non_0
-------: | :--------------------------- | :-------------------------------
20223028 | {48752} | {194907,19260}
20223029 | {48743} | {194945,194907}
20223030 | {48752} | {194907}
20223031 | {48752} | {194907}
dbfiddle here
Related
I have a database table with the following fields :
---------------------
FIELDS : | H1 | H2 | H3 | H4
---------------------
VALUES : | A | B | A | C
---------------------
For a given record (row), I would like to count the number of fields with a value of A. In the above, for example, there are two fields with a value of A, so the expected result would be : 2
How can I achieve this?
I am trying to answer the question from a database point of view.
You have a table with one or more rows and every row has in the four columns either an 'A' or something else. For a given row (or for many rows) you want to get the number of columns that have an 'A' in it.
As one commenter pointed out you can't sum letters but you can check whether or not a value is the one you are looking for and then count this occurence as a 1 or 0. Finally sum those values and return the sum.
SELECT (CASE H1 WHEN 'A' THEN 1 ELSE 0 END) +
(CASE H2 WHEN 'A' THEN 1 ELSE 0 END) +
(CASE H3 WHEN 'A' THEN 1 ELSE 0 END) +
(CASE H4 WHEN 'A' THEN 1 ELSE 0 END) AS number_of_a
FROM name_of_your_table;
For your example row this will return:
NUMBER_OF_A
===========
2
If you have more than one row you'll get the number of As for every row.
I test this it work Thanx for help.
SELECT count(H1) + count(H2) + count(H3) + count(H4) + count(H5) +
count(H6) + count(H7) + count(H8) as TOT
from Table T
where T.H1 = 'A' or T.H2 = 'A' or T.H3 = 'A' or T.H4 = 'A'
or T.H5 = 'A' or T.H6 = 'A' or T.H7 = 'A' or T.H8 = 'A'
group by T.ID
order by 1 DESC
Other solution ...
I have a table which contains a feedback about a product.It has feedback type (positive ,negative) which is a text column, date on which comments made. I need to get total count of positive ,negative feedback for particular time period . For example if the date range is 30 days, I need to get total count of positive ,negative feedback for 4 weeks , if the date range is 6 months , I need to get total count of positive ,negative feedback for each month. How to group the count based on date.
+------+------+----------+----------+---------------+--+--+--+
| Slno | User | Comments | type | commenteddate | | | |
+------+------+----------+----------+---------------+--+--+--+
| 1 | a | aaaa | positive | 22-jun-2016 | | | |
| 2 | b | bbb | positive | 1-jun-2016 | | | |
| 3 | c | qqq | negative | 2-jun-2016 | | | |
| 4 | d | ccc | neutral | 3-may-2016 | | | |
| 5 | e | www | positive | 2-apr-2016 | | | |
| 6 | f | s | negative | 11-nov-2015 | | | |
+------+------+----------+----------+---------------+--+--+--+
Query i tried is
SELECT type, to_char(commenteddate,'DD-MM-YYYY'), Count(type) FROM comments GROUP BY type, to_char(commenteddate,'DD-MM-YYYY');
Here's a kick at the can...
Assumptions:
you want to be able to switch the groupings to weekly or monthly only
the start of the first period will be the first date in the feedback data; intervals will be calculated from this initial date
output will show feedback value, time period, count
time periods will not overlap so periods will be x -> x + interval - 1 day
time of day is not important (time for commented dates is always 00:00:00)
First, create some sample data (100 rows):
drop table product_feedback purge;
create table product_feedback
as
select rownum as slno
, chr(65 + MOD(rownum, 26)) as userid
, lpad(chr(65 + MOD(rownum, 26)), 5, chr(65 + MOD(rownum, 26))) as comments
, trunc(sysdate) + rownum + trunc(dbms_random.value * 10) as commented_date
, case mod(rownum * TRUNC(dbms_random.value * 10), 3)
when 0 then 'positive'
when 1 then 'negative'
when 2 then 'neutral' end as feedback
from dual
connect by level <= 100
;
Here's what my sample data looks like:
select *
from product_feedback
;
SLNO USERID COMMENTS COMMENTED_DATE FEEDBACK
1 B BBBBB 2016-08-06 neutral
2 C CCCCC 2016-08-06 negative
3 D DDDDD 2016-08-14 positive
4 E EEEEE 2016-08-16 negative
5 F FFFFF 2016-08-09 negative
6 G GGGGG 2016-08-14 positive
7 H HHHHH 2016-08-17 positive
8 I IIIII 2016-08-18 positive
9 J JJJJJ 2016-08-12 positive
10 K KKKKK 2016-08-15 neutral
11 L LLLLL 2016-08-23 neutral
12 M MMMMM 2016-08-19 positive
13 N NNNNN 2016-08-16 neutral
...
Now for the fun part. Here's the gist:
find out what the earliest and latest commented dates are in the data
include a query where you can set the time period (to "WEEKS" or "MONTHS")
generate all of the (weekly or monthly) time periods between the min/max dates
join the product feedback to the time periods (commented date between start and end) with an outer join in case you want to see all time periods whether or not there was any feedback
group the joined result by feedback, period start, and period end, and set up a column to count one of the 3 possible feedback values
x
with
min_max_dates -- get earliest and latest feedback dates
as
(select min(commented_date) min_date, max(commented_date) max_date
from product_feedback
)
, time_period_interval
as
(select 'MONTHS' as tp_interval -- set the interval/time period here
from dual
)
, -- generate all time periods between the start date and end date
time_periods (start_of_period, end_of_period, max_date, time_period) -- recursive with clause - fun stuff!
as
(select mmd.min_date as start_of_period
, CASE WHEN tpi.tp_interval = 'WEEKS'
THEN mmd.min_date + 7
WHEN tpi.tp_interval = 'MONTHS'
THEN ADD_MONTHS(mmd.min_date, 1)
ELSE NULL
END - 1 as end_of_period
, mmd.max_date
, tpi.tp_interval as time_period
from time_period_interval tpi
cross join
min_max_dates mmd
UNION ALL
select CASE WHEN time_period = 'WEEKS'
THEN start_of_period + 7 * (ROWNUM )
WHEN time_period = 'MONTHS'
THEN ADD_MONTHS(start_of_period, ROWNUM)
ELSE NULL
END as start_of_period
, CASE WHEN time_period = 'WEEKS'
THEN start_of_period + 7 * (ROWNUM + 1)
WHEN time_period = 'MONTHS'
THEN ADD_MONTHS(start_of_period, ROWNUM + 1)
ELSE NULL
END - 1 as end_of_period
, max_date
, time_period
from time_periods
where end_of_period <= max_date
)
-- now put it all together
select pf.feedback
, tp.start_of_period
, tp.end_of_period
, count(*) as feedback_count
from time_periods tp
left outer join
product_feedback pf
on pf.commented_date between tp.start_of_period and tp.end_of_period
group by tp.start_of_period
, tp.end_of_period
, pf.feedback
order by pf.feedback
, tp.start_of_period
;
Output:
negative 2016-08-06 2016-09-05 6
negative 2016-09-06 2016-10-05 7
negative 2016-10-06 2016-11-05 8
negative 2016-11-06 2016-12-05 1
neutral 2016-08-06 2016-09-05 6
neutral 2016-09-06 2016-10-05 5
neutral 2016-10-06 2016-11-05 11
neutral 2016-11-06 2016-12-05 2
positive 2016-08-06 2016-09-05 17
positive 2016-09-06 2016-10-05 16
positive 2016-10-06 2016-11-05 15
positive 2016-11-06 2016-12-05 6
-- EDIT --
New and improved, all in one easy to use procedure. (I will assume you can configure the procedure to make use of the query in whatever way you need.) I made some changes to simplify the CASE statements in a few places and note that for whatever reason using a LEFT OUTER JOIN in the main SELECT results in an ORA-600 error for me so I switched it to INNER JOIN.
CREATE OR REPLACE PROCEDURE feedback_counts(p_days_chosen IN NUMBER, p_cursor OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_cursor FOR
with
min_max_dates -- get earliest and latest feedback dates
as
(select min(commented_date) min_date, max(commented_date) max_date
from product_feedback
)
, time_period_interval
as
(select CASE
WHEN p_days_chosen BETWEEN 1 AND 10 THEN 'DAYS'
WHEN p_days_chosen > 10 AND p_days_chosen <=31 THEN 'WEEKS'
WHEN p_days_chosen > 31 AND p_days_chosen <= 365 THEN 'MONTHS'
ELSE '3-MONTHS'
END as tp_interval -- set the interval/time period here
from dual --(SELECT p_days_chosen as days_chosen from dual)
)
, -- generate all time periods between the start date and end date
time_periods (start_of_period, end_of_period, max_date, tp_interval) -- recursive with clause - fun stuff!
as
(select mmd.min_date as start_of_period
, CASE tpi.tp_interval
WHEN 'DAYS'
THEN mmd.min_date + 1
WHEN 'WEEKS'
THEN mmd.min_date + 7
WHEN 'MONTHS'
THEN mmd.min_date + 30
WHEN '3-MONTHS'
THEN mmd.min_date + 90
ELSE NULL
END - 1 as end_of_period
, mmd.max_date
, tpi.tp_interval
from time_period_interval tpi
cross join
min_max_dates mmd
UNION ALL
select CASE tp_interval
WHEN 'DAYS'
THEN start_of_period + 1 * ROWNUM
WHEN 'WEEKS'
THEN start_of_period + 7 * ROWNUM
WHEN 'MONTHS'
THEN start_of_period + 30 * ROWNUM
WHEN '3-MONTHS'
THEN start_of_period + 90 * ROWNUM
ELSE NULL
END as start_of_period
, start_of_period
+ CASE tp_interval
WHEN 'DAYS'
THEN 1
WHEN 'WEEKS'
THEN 7
WHEN 'MONTHS'
THEN 30
WHEN '3-MONTHS'
THEN 90
ELSE NULL
END * (ROWNUM + 1)
- 1 as end_of_period
, max_date
, tp_interval
from time_periods
where end_of_period <= max_date
)
-- now put it all together
select pf.feedback
, tp.start_of_period
, tp.end_of_period
, count(*) as feedback_count
from time_periods tp
inner join -- currently a bug that prevents the procedure from compiling with a LEFT OUTER JOIN
product_feedback pf
on pf.commented_date between tp.start_of_period and tp.end_of_period
group by tp.start_of_period
, tp.end_of_period
, pf.feedback
order by tp.start_of_period
, pf.feedback
;
END;
Test the procedure (in something like SQLPlus or SQL Developer):
var x refcursor
exec feedback_counts(10, :x)
print :x
As per application need, Need to do below task in Power Pivot report. (Not in SQL).
I have two date columns in one table
Column Hears :
/* Column Heads :*/ Activity| City | Start_Date | End_Date
/* Row 1 :*/ A1 | C1 | 01/01/2014 | 05/01/2014
/* Row 2 :*/ A1 | C1 | 06/01/2014 | 07/01/2014
/* Row 3 : */ A2 | C2 | 06/01/2014 | 07/01/2014
/* Row 4 : */ A3 | C3 | 03/01/2014 | 04/01/2014
Expected output like - If user selects date range 02/01/2014 to 07/01/2014
Column Header
City | #StartCount| #EndCount
C1 | 1 | 2
C2 | 1 | 1
C3 | 1 | 1
Here #StartCount is
Need to grouped by City.
Its Count of Distinct Activity
It should consider date boundries as : All activity for which start date 'greater or equeal(>=)' Input Start date and (less than '<') End Date
Here #EndCount is
Need to grouped by City.
Its Count of Distinct Activity
It should consider date boundries as : All activity for which Ends date 'Less or equeal(<=)' Input End date and (Greater than '>') End Date
Could you please suggest me expression to be used for such case.
Calculated measure or dax can be used..
The only way I can match your sample data is to ignore the "distinct activities" requirement in your question, since city C1 has only activity A1 and yet the final result counts to 2.
I'm also probably making a lot of assumptions that may be wrong because your sample data is quite limited. But here's my attempt:
declare #Activities table (Activity char(2),City char(2),Start_Date date,End_Date date)
insert into #Activities (Activity,City,Start_Date,End_Date) values
('A1','C1','20140101','20140105'),
('A1','C1','20140106','20140107'),
('A2','C2','20140106','20140107'),
('A3','C3','20140103','20140104')
declare #Start date
declare #End date
select #Start = '20140102', #End = '20140107'
select City,
SUM(CASE WHEN Start_Date < #Start THEN 0 ELSE 1 END) as StartCount,
SUM(CASE WHEN End_Date > #End THEN 0 ELSE 1 END) as EndCount
from #Activities where Start_Date < #End and End_Date > #Start
group by City
(Some of this relies on SQL Server syntax, but since you haven't tagged your question with a database system, I get to pick)
SQL Server syntax
select activity, city,
SUM(case when (startdate >= '2014/01/02' and startdate <= '2014/01/07') then 1 else 0 End) as IsStart,
SUM(case when (enddate >= '2014/01/02' and enddate <='2014/01/07') then 1 else 0 End) as IsEnd
from temp
Group by activity, city
demo: http://sqlfiddle.com/#!3/b2a64/1
In a query below I count how many reviews and comments publication have. I summing up reviews and comments like that: .select('"publications".*, count("reviews".id) + count("comments".id) as my_count').
Assuming publication have 3 reviews and 3 comments in sum would be 6, however my_count always shows bigger number. What is happening behind the curtain and how to make it count normally?
Publication.joins(:reviews, :comments)
.select('"publications".*, count("reviews".id) + count("comments".id) as my_count')
.group('"publications".id')
.order("my_count DESC")
The generated SQL probably looks like this:
SELECT publications.id, COUNT(reviews.id) + COUNT(comments.id) AS my_count
FROM publications p
INNER JOIN reviews r ON p.id = r.publication_id
INNER JOIN comments c ON p.id = c.publication_id
GROUP BY p.id
ORDER BY my_count DESC
Let's get rid of grouping for a moment and see what's going on on the following input:
publications: [{ id: 1 }],
reviews: [{ publication_id: 1, id: 1 }, { publication_id: 1, id: 2 },{ publication_id: 1, id: 3 }]
comments: [{ publication_id: 1, id: 10 }, { publication_id: 1, id: 20 }]
So there are are 3 reviews and 2 comments. However, this query will return 6 rows:
SELECT *
FROM publications p
INNER JOIN reviews r ON p.id = review.publication_id
INNER JOIN comments c ON p.id = comment.publication_id
publication.id | review.id | comment.id
1 | 1 | 10
1 | 2 | 10
1 | 3 | 10
1 | 1 | 20
1 | 2 | 20
1 | 3 | 20
And, when you group it, it will return 6+6 = 12 as a total count.
One possible workaround is to do COUNT(DISTINCT reviews.id) + COUNT(DISTINCT comments.id). Probably, this is not the best solution in terms of performance.
As DNNX points out, this occurs because you have fallen into what is called a "Chasm trap" -- the row count is inflated because of the multiple one-to-many joins.
You could try this as a shortterm alternative:
Publication.select('"publications".*,
coalesce((select count(*) from reviews r where r.publication_id = pubications.id),0)
+ coalesce((select count(*) from comments c where c.publication_id = pubications.id),0) as my_count')
.order("my_count DESC")
However I'd suggest you place counter caches on Publication for reviews and comments.
I'm developing and iOS game and I want to switch cols and rows
For example here is the stat's table :
StatName (STRING) | StatValue (NUMBER)
--------------------------------------
NbJoker | 12
--------------------------------------
NbPlayed | 71
--------------------------------------
NbPause | 87
--------------------------------------
I need
NbJoker | NbPlayed | NbPause
----------------------------
12 | 71 | 87
Is that possible ?
Thanks!
I do not know SQL Lite. But If the below syntax works.
It's like the same as a Transpose in any SQL.
SELECT SUM(T1) AS NBJOKER, SUM(T2) AS NBPLAYED, SUM(T3) AS NBPAUSE FROM (
SELECT STATVALUE AS T1,O AS T2,0 AS T3 FROM TABLE_X WHERE STATNAME='NBJOKER'
UNION ALL
SELECT 0, STATVALUE, 0 FROM TABLE_X WHERE STATNAME='NBLAYED'
UNION ALL
SELECT 0, 0, STATVALUE FROM TABLE_X WHERE STATNAME='NBPAUSE'
)