Help for a Sql statement - sql

Hy at all, today is the day of ...question.
I've a single table, with a relation master-detail like this:
RecordID MasterID Field1 Field2 .... NrDetail
1 0 xxx yyyy 1
2 0 aaaa bbbb 2
3 1 hhhhh ssss 0
4 2 eee sssss 0
5 2 jjj hhhh 0
As you can see, NrDetail contain the total of "child record".
Unfortunately, i've to create this field... and i would like to write it in my table.
So my SQL question is: how to do this type of SQL to write the field NrDetail ?
Something like:
UPDATE table SET NrDetail=
(SELECT COUNT(*) as Total FROM table WHERE MasterID= RecordID)
But i think there's some mistake...
Thank you in advance !

I think that you have forgetten to specify which MasterID you want to compare with which RecordID.
How about:
UPDATE table t1 SET NrDetail=
(SELECT COUNT(*) as Total FROM table t2 WHERE t1.MasterID=t2.RecordID)

UPDATE table
SET NrDetail = (
Select Count(*)
FROM table t2
Where t2.RecordID = table.MasterID
)
In an update statement, when you want to reference the table being updated, you need to use the full reference for columns(tablename.columnname, or ideally schema.tablename.columnname). If you are using the same table in a subquery, you need to alias the table in the subquery but again use the full reference for the outer table.
ADDITION Since you mentioned that you are using MySql, you could try something like so:
Update post
Join (
Select p1.idpadre, Count(*) Total
From post p1
Group By p1.idpadre
) Z
On Z.idpadre = post.idpost
Set post.NrDetail = Z.Total

Related

How to write sql clause where column not equal and any id associated

I want to setup a simple query that will filter out any row that contains "A" in the ItemID, but my issue is I also do NOT want to display any journal ID from a different row since it matched "A". I tried googling the solution, but I am sure I am not using the right keywords to find it. I am using microsoft sql 2008, but I am not a database admin so I am not to familiar. I tried using distinct, and I also tried group by, but in this situation it does not work.
This is a simplified version of the table that I am working with:
JournalID ItemID PrimaryKEY
1 A 1
1 B 2
2 A 3
2 C 4
3 B 5
4 D 6
And here is how I would like to make it look:
JournalID ItemID PrimaryKEY
3 B 5
4 D 6
This will exclude any rows where the ItemID is 'A' and also any rows that have the same JournalID as a row where a ItemID was 'A'.
SELECT JournalID, ItemID, PrimaryKEY
FROM TABLE
WHERE JournalID NOT IN (Select JournalID FROM TABLE WHERE ItemID = 'A')
Try this:
SELECT *
FROM table_name
WHERE JournalID
NOT IN (SELECT JournalID
FROM table_name
WHERE ItemID = 'A')

SQL select entries from table where atribute equals parameter else select * entries

It is possible in SQL (ORACLE) to select all entry from a table where an atribute equals an parameter and if not select all the others entries?
like in this example:
COD | Name
1 | Monday
2 | Thursday
3 | Saturday
parameter=3
when cod equals parameter(cod=3) return entry of cod parameter(cod=3) (including cod and name)
else
return all others entries different from parameter(cod=3) (including cod and name) (like 1 Monday and 2 Thursday)
Is it possible with SQL (oracle), or i need something like PLSQL?
I'd use a correlated query and a non-correlated query:
SELECT COD, NAME
FROM TABLE a
WHERE EXISTS (SELECT 1 FROM TABLE b WHERE b.COD = a.COD AND b.COD = 3)
OR NOT EXISTS (SELECT 1 FROM TABLE c WHERE c.COD = 3)
I'm not sure if I'm following your logic, entirely, however.
And, actually, in cases where it's all from one table it can be simplified to just:
SELECT COD, NAME
FROM TABLE a
WHERE a.COD = 3
OR NOT EXISTS (SELECT 1 FROM TABLE c WHERE c.COD = 3)
IF EXISTS(SELECT 1 FROM TABLE WHERE COD=3)
THEN
SELECT COD, NAME FROM TABLE WHERE COD=3
ELSE
SELECT COD, NAME FROM TABLE
END IF

Update with results of another sql

With the sql below I count how many records I have in tableB for each code. The total field is assigned the result of the count and the code the code field of the record.
SELECT
"count" (*) as total,
tableB."code" as code
FROM
tableB
WHERE
tableB.code LIKE '%1'
GROUP BY
tableB.code
In tableA I have a sequence field and I update with the result of total (obtained in the previous sql) plus 1 Do this for each code.
I tried this and it did not work, can someone help me?
UPDATE tableA
SET tableA.sequence = (tableB.total + 1) where tableA."code" = tableB.code
FROM
(
SELECT
"count" (*) as total,
tableB."code" as code
FROM
tableB
WHERE
tableB.code LIKE '%1'
GROUP BY
tableB.code
)
I edited for my tables are as mostar believe facillita understanding of my need
tableA
code sequence
100 null
200 null
table B
code sequence
100 1
100 2
100 3
100 4
......
100 17
200 1
200 2
200 3
200 4
......
200 23
Need to update the sequence blank field in tableA with the number 18 to code = 100
Need to update the sequence blank field in tableA with the number 24 to code = 200
This assumes that code is unique in table_a:
with max_seq as (
select code,
max(sequence) + 1 as max_seq
from table_b
group by code
)
update table_a
set sequence = ms.max_seq
from max_seq ms
where table_a.code = ms.code;
SQLFiddle example: http://sqlfiddle.com/#!15/745a7/1
UPDATE tbl_a a
SET sequence = b.next_seq
FROM (
SELECT code, max(sequence) + 1 AS next_seq
FROM tbl_b
GROUP BY code
) b
WHERE a.code = b.code;
SQL Fiddle.
Only columns of the target table can be updated. It would not make sense to table-qualify those. Consequently, this is not allowed.
Every subquery must have a table alias for the derived table.
I would not use a CTE for a simple UPDATE like this. A subquery in the FROM clause is typically simpler and faster.
No point in double-quoting the aggregate function count(). No pint in double-quoting perfectly legal, lower case identifiers, either. No point in table-qualifying columns in a subquery on a single table in a plain SQL command (no harm either).
You don't need a WHERE condition, since you want to UPDATE all rows (as it seems). Note that only row with matching code are updated. Other rows in tbl_b remain untouched.
Basically you need to read the manual about UPDATE before you try any of this.

How to get filtered records from Sql Server 2005?

Consider that I have two tables.
One is "Table1" as shown below.
One more table is "Table2" as shown below.
Now here what I need is, I need all the records from Table1 those ID's are not in Table2's Reference column.
Please guide me how to do this.
Thanks in advance.
How to do it with your current schema (impossible to use indexes):
SELECT Table1.*
FROM Table1
WHERE NOT EXISTS
(
SELECT 1
FROM Table2
WHERE CONCAT(',', Table2.Reference, ',') LIKE CONCAT('%,', Table1.ID, ',%')
)
How this works is by completely wrapping every value in the Reference column with commas. You will end up with ,2,3, and ,7,8,9, for your sample data. Then you can safely search for ,<Table1.ID>, within that string.
How to really do it:
Normalize your database, and get rid of those ugly, useless comma-separated lists.
Fix your table2 to be:
SlNo | Reference
------+-----------
1 | 2
1 | 3
2 | 7
2 | 8
2 | 9
and add a table2Names as:
SlNo | Name
------+---------
1 | Test
2 | Test 2
Then you can simply do:
SELECT Table1.*
FROM Table1
WHERE NOT EXISTS(SELECT 1 FROM Table2 WHERE Table2.Reference = Table1.ID)

How do I count unique items in field in Access query?

My Table: table1
ID Name Family
1 A AA
2 B BB
3 A AB
4 D DD
5 E EE
6 A AC
SQL command on Access:
select count(*) from table1
Output: ------------> True
6 row(s)
I tried to count unique names:
Expected output: 4 row(s)
select count(distinct Name) from table1
Output on Access: ------------> Error
What changes do I need to make to my query?
Try this
SELECT Count(*) AS N
FROM
(SELECT DISTINCT Name FROM table1) AS T;
Read this for more info.
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:
SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
SELECT First([FieldName]) AS [UniqueField]
FROM TableName
GROUP BY [FieldName]
HAVING (((Count([FieldName]))>0))
);
Hope this helps, not the best way I am sure, and Access should have had this built in.