I'd appreciate if someone could help. I have two tables that have no relationship:
Table_1
ID credittype creditamount date time
------------------------------------
1 abc 10 2016-01-18 11:29:59 am
2 def 20 2016-01-20 4:35:58 pm
3 def 20 2016-01-21 4:35:58 pm
Table_2
ID debitetype debiteamount date time
------------------------------------
1 abc 10 2016-01-18 11:29:59 am
2 def 20 2016-01-19 4:35:58 pm
3 def 20 2016-01-21 4:35:58 pm
i just want to display these tables values
like that
credittype creditamount debitetype debiteamount date time
---------------------------------------------------------
abc 10 2016-01-18 11:29:59 am
def 20 2016-01-19 4:35:58 pm
def 20 2016-01-20 4:35:58 pm
i will try this query
select * from Table_1 union select * from Table_2;
i did not get answer any one help me?
Using union only gets distinct values from both tables. Try using "union all" to return all values. Refer to http://www.w3schools.com/sql/sql_union.asp.
Note , joining 2 table that don't have any condition not good , and it discovered that you don't design your database structure very well.
so , try like this :
select tb1.credittype,tb1.creditamount,tb1.debitetype,tb1.debiteamount,tb1.date,tb1.time from table1,table2
it gives you all record in table one and table two
Related
I have many weekly backup tables of the same structure and columns but with different names containing some user-specific information like this.
user_details
user_details_20211126
user_details_20211119
user_details_20211112
and so on....
Now I want to find the tables within a date range for example: If I choose the date range of 2021-11-20 to 2021-11-13 then the tables fetched would be user_details, user_details_20211126, user_details_20211119 for using them in a query containing union operation on all the fetched tables.
Any idea on how to do that?
As already commented, what an awful idea ... you shouldn't be doing it that way. One table with a DATE datatype column should by the way to do it. I suggest you switch to it - the sooner, the better.
Meanwhile - although you didn't name database you use & I'm using Oracle - here's what you'll probably have to do, regardless of the database: some kind of dynamic SQL as you have to "dynamically" compose the SELECT statement, using only tables that satisfy the condition. As you have to fetch their names from the data dictionary, you don't have many options but - as I said - dynamic SQL.
OK, here you go.
Setting date format (you don't have to do that):
SQL> alter session set nls_date_format = 'dd.mm.yyyy';
Session altered.
Tables whose names are user_details_something:
SQL> select table_name
2 from user_tables
3 where table_name like 'USER_DETAILS%'
4 order by table_name;
TABLE_NAME
------------------------------
USER_DETAILS
USER_DETAILS_20211126
USER_DETAILS_20211127
USER_DETAILS_20211128
How to select only tables whose name contains date that is between desired values?
query data dictionary (in Oracle, that's user_tables)
extract the DATE part of their names (I chose regexp_substr function; you'd use any you find appropriate)
convert extracted substring into a valid date value (using TO_DATE function)
Therefore:
SQL> select table_name
2 from user_tables
3 where table_name like 'USER_DETAILS%'
4 and to_date(regexp_substr(table_name, '\d+$'), 'yyyymmdd')
5 between date '2021-11-26' and date '2021-11-27';
TABLE_NAME
------------------------------
USER_DETAILS_20211126
USER_DETAILS_20211127
OK; two tables between 26.11.2021 and 27.11.2021 (I didn't feel like creating more of them).
The second part of the job is to actually fetch data from those tables. Here's a function that accepts date period as parameters and returns ref cursor (you can choose something else, of course). Read comments within code:
SQL> create or replace function f_test(par_date_from in date,
2 par_date_to in date)
3 return sys_refcursor
4 is
5 l_str varchar2(1000); -- contains the whole SELECT statement
6 rc sys_refcursor;
7 begin
8 -- loop through all tables whose names satisfy the condition
9 for cur_r in
10 (select table_name
11 from user_tables
12 where table_name like 'USER_DETAILS%'
13 and to_date(regexp_substr(table_name, '\d+$'), 'yyyymmdd')
14 between par_date_from and par_date_to
15 ) loop
16 -- compose a SELECT statement
17 l_str := l_str ||
18 'select ename, job, datum from ' || cur_r.table_name || ' union all ';
19 end loop;
20
21 -- remove trailing UNION ALL
22 l_str := rtrim(l_str, ' union all');
23
24 -- open and return ref cursor
25 open rc for l_str;
26 return rc;
27 end;
28 /
Function created.
OK, let's try it:
SQL> select f_test(date '2021-11-26', date '2021-11-27') from dual;
F_TEST(DATE'2021-11-
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
ENAME JOB DATUM
---------- --------- ----------
SMITH CLERK 26.11.2021
JONES MANAGER 26.11.2021
SCOTT ANALYST 26.11.2021
ADAMS CLERK 26.11.2021
FORD ANALYST 26.11.2021
ALLEN SALESMAN 27.11.2021
WARD SALESMAN 27.11.2021
MARTIN SALESMAN 27.11.2021
BLAKE MANAGER 27.11.2021
TURNER SALESMAN 27.11.2021
JAMES CLERK 27.11.2021
11 rows selected.
SQL>
It works for me; I hope you won't have to make it "work" at all, but - after you apply what we've already suggested - run a simple
SQL> select * from user_details
2 where datum between date '2021-11-26' and date '2021-11-27';
DEPTNO EMPNO ENAME JOB DATUM
---------- ---------- ---------- --------- ----------
20 7369 SMITH CLERK 26.11.2021
20 7566 JONES MANAGER 26.11.2021
20 7788 SCOTT ANALYST 26.11.2021
20 7876 ADAMS CLERK 26.11.2021
20 7902 FORD ANALYST 26.11.2021
30 7499 ALLEN SALESMAN 27.11.2021
30 7521 WARD SALESMAN 27.11.2021
30 7654 MARTIN SALESMAN 27.11.2021
30 7698 BLAKE MANAGER 27.11.2021
30 7844 TURNER SALESMAN 27.11.2021
30 7900 JAMES CLERK 27.11.2021
11 rows selected.
SQL>
Obviously, my user_details table contains the DATE datatype column and makes everything A LOT simpler.
I am writing a web application in PHP with MySQL.
I have a table called counts and this is how data is stored in that table:
Table: counts
id counts location_id media_id created_at
--------------------------------------------------
1 50 1 1 2017-03-15
2 30 2 1 2017-03-15
3 80 1 2 2017-03-15
4 20 1 1 2017-03-16
5 100 2 2 2017-03-16
For every unique location_id, media_id and created_at, I store count.
I have another table locations which is like this:
Table: locations
id name
----------------
1 Location 1
2 Location 2
3 Location 3
4 Location 4
5 Location 5
This is the SQL Query I have at the moment:
select sum(counts.count) as views, locations.name as locations, DAYNAME(counts.created_at) AS weekday from `counts` inner join `locations` on `locations`.`id` = `counts`.`location_id` where `counts`.`created_at` between '2016-12-04' and '2016-12-10' group by `weekday`, `counts`.`location_id`;
This is how the data is displayed:
locations weekday views
-----------------------------------
Location 1 Mon 50
Location 1 Tue 30
Location 2 Mon 20
Location 2 Tue 70
I'm creating reports and I would like to run a query such that all the days of the week appear as a column with their corresponding values as the view count for that day of the week. I want something like this:
locations mon tue wed thu fri sat sun
-------------------------------------------------
Location 1 40 60 51 20 40 20 30
Location 2 80 60 100 24 30 10 5
Is the above possible in MySQL or I would have to use PHP to achieve that? If so, how do I go about it?
Any help will be appreciated, thanks.
NB: The sample data is not accurate.
It's possible to achieve this result with MySQL, using conditional aggregation.
The trick is to use a conditional test in an expression in the SELECT list to determine whether to return a value of count.
Something like this:
SELECT l.name AS `locations`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Mon',c.count,0)) AS `mon`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Tue',c.count,0)) AS `tue`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Wed',c.count,0)) AS `wed`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Thu',c.count,0)) AS `thu`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Fri',c.count,0)) AS `fri`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sat',c.count,0)) AS `sat`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sun',c.count,0)) AS `sun`
FROM `locations` l
LEFT
JOIN `counts` c
ON c.location_id = l.id
AND c.created_at >= '2016-12-04'
AND c.created_at < '2016-12-04' + INTERVAL 7 DAY
GROUP BY l.name
ORDER BY l.name
NOTE:
With the sample data, there are two rows for location_id=1 and created_at='2016-03-15', so this query would return a total of 130 for tue (=50+80), not 50 (as shown in the sample output of the existing query).
I am facing a problem I am not capable to solve on my own. There a several questions out that regarding counting but I did no see one where the counting is done like I would need it. In my table I have three slots that can be booked by a Person, represented by their ID, like this:
ID | Slot1 | Slot2 | Slot3
1 45 53
2 1 27 6
3 53
4 6 45
5 15 53
It is possible that slots are free but it is not possible that an ID blocks to slots.
Now I would like to count how often each ID used on of the three slots. The result would look like this for the table above:
ID Count
1 1
6 2
15 1
27 1
45 2
53 3
Is that possible with one mysql statement or do I need to GROUP BY for each slot and add the slots up later in my script?
If it is possible to do the counting in mysql over all three slots, would it also be possible to join the result with a second table that holds the names to the IDs?
You want a union all and aggregation:
select slot, count(*)
from ((select slot1 as slot from t
) union all
(select slot2 as slot from t
) union all
(select slot3 as slot from t
)
) s
where slot is not null
group by slot
You can use UNION :
SELECT s.SLOT_ID, COUNT(*)
FROM (
SELECT slot1 as slot_id FROM YourTable
UNION ALL
SELECT slot2 FROM YourTable
UNION ALL
SELECT slot3 FROM YourTable ) s
GROUP BY s.slot_id
For example I have table:
| id | title | created_at |
1 12:00
2 13:00
2 14:00
1 15:00
I want same id numbers to be near each other. In this case 1 1 2 2 or 2 2 1 1 AND order same chunks of id's by created_at time so the chunk of id's which own the latest created_at stays on top, then goes one, having highest created_at compared to 3rd chunk of id's and so on. How do I do it?
orderBy('id', 'desc')->orderBy('created_at', 'desc')->get(); // orders id's to same id chunks, but it doesn't sort that the chunk with latest id chunk (1 1) created_at at the top.
orderBy('created_at', 'desc')->orderBy('id', 'desc')->get(); // gives the latest created_at at top and so on, but same id's arent close to each other.
Bigger example:
| id | title | created_at |
1 12:00
2 13:00
1 15:00
2 15:00
1 17:00
3 18:00
1 19:00
3 20:00
Want to anchieve that foreach($table_rows as $row) { } would give me result:
3 20:00
3 18:00
1 19:00
1 17:00
1 15:00
1 12:00
2 15:00
2 13:00
I know it's hard to do with mysql alone. How do I do this in php easiest way?
I bet I have to sort by id first and then push each id's chunk relative to each other by latest created_at.
You need to get the information of the most recent date for each id. Here is a method using join and an aggregation:
select t.*
from table t join
(select t.id, max(created_at) as maxca
from table t
group by t.id
) tt
on t.id = tt.id
order by tt.maxca desc, id;
The rest is just the order by using the maximum value.
I don't know how to express this in laravel, but your question is also tagged mysql.
categories and scheduler
categories
id name start_date end_date
1 cat1 2014-04-02 00:00:00 2014-04-12 10:00:00
2 cat2 2014-04-12 12:00:00 2014-04-12 13:00:00
3 cat3 2014-04-01 00:00:00 2014-04-12 11:00:00
and scheduler table is
id name firetime runonce
1 1 1397651700 1
2 1 1397652200 2
3 2 1397654100 2
like this. In scheduler table, name is categories table's id and firetime is strtotime of start_date and end_date. runonce called start_date and end_date reference.
If the firetime less than now date, it automatically deleted, but not categories. Here I want to sort by firetime which is ready for next fire. And fired categories should show below.
My query is:
SELECT * FROM categories ORDER BY sale_start_date, sale_end_date
Here, how to match with scheduler table and sort by upcoming fire date.
Try:
SELECT * FROM scheduler ORDER BY firetime
Your database has a very bad structure. Columns representing the same thing (date/time values) have different formats. Foreign key references have no name similarity (id, name).
I think you want a join and aggregation. Based on the information in your question, it is something like this:
SELECT c.*
FROM categories c join
scheduler s
on s.firetime between strtotime(sale_start_date) and strtotime(sale_end_date) and
s.name = c.id
ORDER BY sale_start_date, sale_end_date;